描述
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
语法
super(type[, object-or-type])
type – 类。
object-or-type – 类,一般是 self
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx
super().add(x)
super(B, self).add(x)
other: 构造方法
> __init__()
初始化新创建对象的状态,在一个对象被创建以后会立即调用。(即初始化)
构造方法中的初始值无法继承
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print ('Ahahahah')
else:
print ('No thanks!')
class SongBird(Bird):
def __init__(self):
self.sound = 'Squawk'
def sing(self):
print (self.sound)
sb = SongBird()
sb.sing() # 能正常输出
sb.eat() # 报错,因为 songgird 中没有 hungry 特性
解决办法:使用super函数
class SongBird(Bird):
def __init__(self):
super().__init__()
self.sound = 'Squawk'
def sing(self):
print (self.sound)
使用 super() 可以很好地避免构造函数被调用两次。
class A():
def __init__(self):
print('enter A')
print('leave A')
class B(A):
def __init__(self):
print('enter B')
super().__init__()
print('leave B')
class C(A):
def __init__(self):
print('enter C')
super().__init__()
print('leave C')
class D(B, C):
def __init__(self):
print('enter D')
super().__init__()
print('leave D')
d = D()
'''
enter D
enter B
enter C
enter A
leave A
leave C
leave B
leave D
'''