类继承:错误提示对象没有属性

时间:2019-11-02 14:27:13

标签: python class object inheritance attributes

每当我尝试在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.")

1 个答案:

答案 0 :(得分:0)

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