>>>b = Bird()
>>>b.eat()
Eating...
>>>b.eat()
No, thanks.
这时候,如果创建的Bird的子类没有调用Bird的构造函数的话,子类在调用涉及到超类初始化的属性时就会报错
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print("Eating...")
self.hungry = False
else:
print("No, thanks.")
class SongBird(Bird):
def __init__(self):
self.sound = 'Squawk!'
def sing(self):
print(self.sound)
>>>sparrow = SongBird()
>>>sparrow.sing()
Squawk!
>>>sparrow.eat()
Traceback (most recent call last):
File "xxx", line 21, in <module>
sparrow.eat()
File "xxx", line 5, in eat
if self.hungry:
AttributeError: 'SongBird' object has no attribute 'hungry'