前言:
super() 函数是用于调用父类(超类)的一种方法,具体可点击这里查看。
示例代码:
1.创建两个单独的类;
类Bird实现所有鸟的基本能力:进食。第一次进食输出“Aaaah...”;第二次进食输出“No,thanks!”
类SongBird实现鸟的部分能力:唱歌。调用song函数输出"squawk!"
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:
def __init__(self):
self.sound = 'Squawk!'
def sing(self):
print(self.sound)
a = Bird()
a.eat()
a.eat()
b = SongBird()
b.sing()
结果: Aaaah... No,thanks! Squawk!
2.创建两个类,其中子类调用父类。
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)
b = SongBird()
b.sing()
b.eat()
结果:
Squawk!
Traceback (most recent call last):
File "/media/zhangwentao/DATA1/Documents2/tensorflow2.0/CNN/003.py", line 27, in <module>
b.eat()
File "/media/zhangwentao/DATA1/Documents2/tensorflow2.0/CNN/003.py", line 7, in eat
if self.hungry:
AttributeError: 'SongBird' object has no attribute 'hungry'
问题分析:
因为在SongBird中重写了构造函数,但新的构造函数没有包含任何初始化属性hungry的代码。
解决方法:
①调用未关联的超类构造函数;②使用函数super
3.修改后的代码:
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) # ①调用未关联的超类构造函数
# super().__init__() # ②使用super函数
self.sound = 'Squawk!'
def sing(self):
print(self.sound)
b = SongBird()
b.sing()
b.eat()
b.eat()
结果:
Squawk!
Aaaah...
No,thanks!
参考资料:
1.python基础教程(第3版)p147