【问题标题】:Assign different variables to different classes将不同的变量分配给不同的类
【发布时间】:2014-06-06 21:43:21
【问题描述】:

我正在学习 Python 教程系列,并且已经开始上课了。 所以..我正在尝试制作某种“中世纪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

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

【问题讨论】:

    标签: python class oop object


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      def __init__(self, name, wep_name) 
      

      就像你在武器课上所做的那样。

      现在可以了

      self.equipment["Weapon"] = wep_name 
      

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

      希望对你有所帮助

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多