【问题标题】:Class Inheritance: error saying that object has no attribute类继承:错误说对象没有属性
【发布时间】:2019-11-02 14:27:13
【问题描述】:

每当我尝试在 vampire(monster) 类中运行 sleep 方法时,都会发生以下错误: AttributeError: 'vampire' object has no attribute 'hasCastle' 该错误链接到代码的第 8 行。 我不明白为什么会发生这种情况,因为我是继承新手。

代码:

class vampire(monster):
    def _init__(self, givenHasCastle, givenStrength, givenName):
        super().__init__(givenStrength, givenName)
        self.hasCastle = givenHasCastle

    def drinkBlood(self):
            print(self.name+" the vampire drinks the hero's blood.")

    def sleep(self):
        if self.hasCastle == True:
         print("The vampire sleeps silently in their castle.")
        else:
            print("The vampire sleeps silently in the wilderness.")

【问题讨论】:

  • 错字:__init__ 缺少下划线

标签: python class object inheritance attributes


【解决方案1】:

hasCastle 将充当局部变量,将其声明为类变量不会显示该错误。

【讨论】:

  • 到处都没有hasCastle局部变量,代码只引用了self的self.hasCastle属性,这个属性不存在(参考错误信息),因为名字的拼写错误__init__,如评论中所述。请注意,不应回答此类错字问题,因为它们的命运是被关闭和删除。在此之前发表评论以帮助 OP 注意到就足够了。
猜你喜欢
  • 2023-04-02
  • 2012-05-03
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多