从另一个模块导入函数:AttributeError:'module'对象没有属性

时间:2017-03-25 16:23:27

标签: python class

我正在进行类似程序的战斗,其中有一个模块包含创建角色类的函数和一个主代码所在的模块。当我导入一个函数来改变其中一个字符的健康状况时,我得到一个错误说:

AttributeError: 'module' object has no attribute

这是功能:

def changeHealth(self,health,defense,Oattack):
    self.health = health - (Oattack - defense) - 15
    return self.health

当我在主代码模块上调用该函数时,我这样做:

import CharacterClass 
CharacterClass.changeHealth(self,health,defense,Oattack)

1 个答案:

答案 0 :(得分:1)

以下是如何为Character创建可用于程序中任何角色的类的示例。每个类应代表一种独特的对象类型,在本例中为“字符”。每个字符都应该是该类的一个实例。然后,您可以使用函数或类方法处理字符实例之间的交互。

class Character(object):
    def __init__(self, name, attack, defense, health):
        self.name = name
        self.attack = attack
        self.defense = defense
        self.health = health

    def injure(self, damage):
        self.health = self.health - damage

    def __str__(self):
        return "Character: {}, A:{}, D:{}, H:{}".format(self.name, self.attack, self.defense, self.health)

    def check(self):
        print("this works")

    def doAttack(self, other=None):
        dmg = self.attack - other.defense
        if dmg > 0: 
            other.injure(dmg)
            print("{} caused {} damage to {}".format(self.name, dmg, other.name))
        else:
            print("{} did not injure {}".format(self.name, other.name))


hero = Character('Hero', 8, 10, 20)
opponent = Character('Monster', 4, 5, 10)


opponent.doAttack(hero)
print(hero)
print(opponent)
print()

hero.doAttack(opponent)
print(hero)
print(opponent)
print()

运行此代码会产生:

Monster did not injure Hero
Character: Hero, A:8, D:10, H:20
Character: Monster, A:4, D:5, H:10

Hero caused 3 damage to Monster
Character: Hero, A:8, D:10, H:20
Character: Monster, A:4, D:5, H:7

这是一个非常基本的例子。您可能需要阅读Object Oriented Programming in Python(或类似的文本)来了解构造面向对象代码背后的概念。