class Bird:
def __init__(self): #构造函数
self.hungry=True
def eat(self):
if self.hungry:
print("Aaaah.....")
self.hungry=False
else:
print("No, thanks!")
class SongBird(Bird):
def __init__(self):
self.sound="Squawk!"
def sing(self):
print(self.sound)
sb=SongBird()
sb.sing()
运行结果为为:
Squawk!
但是当运行sb.eat()
时,会有如下报错:
'SongBird' object has no attribute 'hungry'
因为在SongBird中重写了构造函数,但新的构造函数没有包含任何初始化属性hungry的代码。
要消除这个错误,SongBird的构造函数必须调用其超类(Bird)的构造函数,以确保基本的初始化得以执行。为此,有两种方法:
1) 调用未关联的超类的构造函数
class Bird: #超类
def __init__(self): #构造函数
self.hungry=True
def eat(self):
if self.hungry:
print("Aaaah.....")
self.hungry=False
else:
print("No, thanks!")
class SongBird(Bird): #子类
def __init__(self):
Bird.__init__(self) #使用未关联的超类的构造函数
self.sound="Squawk!"
def sing(self):
print(self.sound)
sb=SongBird()
sb.sing()
sb.eat()
运行结果:
Squawk!
Aaaah.....
2) 使用函数Super
class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print("Aaaah.....")
self.hungry=False
else:
print("No, thanks!")
class SongBird(Bird):
def __init__(self):
super().__init__() ###使用super函数,相当于调用了超类的构造函数。
self.sound="Squawk!"
def sing(self):
print(self.sound)
sb=SongBird()
sb.sing()
sb.eat()
运行结果:
Squawk!
Aaaah.....