繁体   English   中英

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

[英]Assign different variables to different classes

我正在学习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

对不起,如果标题没有意义。 我不确定这叫什么:(

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

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

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

你必须像这样将它提供给你的init方法

def __init__(self, name, wep_name) 

就像你在武器类中所做的那样。

现在你可以做到

self.equipment["Weapon"] = wep_name 

否则考虑引用已经封装了weapon_name的武器类的实例

希望这可以帮助你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM