将不同的变量分配给不同的类

时间:2014-06-06 21:43:22

标签: python class oop object

我正在学习Python教程系列,并且我已经上课了。 所以..我试图制作一些" medevial​​ RPG类系统"并试图将武器送到武士班。我真的很陌生,所以如果你们解释它尽可能简单,那就太感恩了。

所以,我收到一个错误:

AttributeError: 'Warrior' object has no attribute 'wep_name'

我做错了什么?

以下是代码:

class Character(object):
    def __init__(self, name):
        self.health = 100
        self.name = name
        self.equipment = {

        "Weapon": 'None',
        "Attack Damage": '0'
        }

    def printName(self):
        print "Name: " + self.name


class Warrior(Character):
    """
    **Warrior Class**
    50%  more HP
    """
    def __init__(self, name):
        super(Warrior, self).__init__(name)
        self.health = self.health * 1.5
        self.equipment["Weapon"] = self.wep_name      # <-- ?

class Weapon(object):
    def __init__(self, wep_name):
        self.wep_name = wep_name

如果标题毫无意义,那就很抱歉。我不确定这叫什么:(

2 个答案:

答案 0 :(得分:2)

在包含错误的行中,self指的是Warrior,而不是Weapon,因此它没有wep_name。如果你想在那时创建一个新的Weapon,它可能是这样的:

    self.equipment["Weapon"] = Weapon("Sword")

答案 1 :(得分:1)

由于你的战士类中没有武器成员变量,你无法分配它。

您必须将它提供给您的init方法,如此

def __init__(self, name, wep_name) 
就像你在武器类中一样。

现在你可以做到

self.equipment["Weapon"] = wep_name 

否则考虑引用已经封装了weapon_name

的武器类的实例

希望这可以帮助你

相关问题