描述
super() 函数是用于调用父类(超类)的一个方法。
super() 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
语法
以下是 super() 方法的语法:
super(type[, object-or-type])
参数
- type -- 类。
- object-or-type -- 类,一般是 self
Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx
Python3.x 实例:
class A:
def add(self, x):
y = x+1
print(y)
class B(A):
def add(self, x):
super().add(x)
b = B()
b.add(2) # 3
返回值
无。
实例
以下展示了使用 super 函数的实例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent)
# 然后把类 FooChild 的对象转换为类 FooParent 的对象
super(FooChild,self).__init__()
print ('Child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
执行结果:
Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.
Python3 中继承遵循广度优先原则:
class A:
def __init__(self):
print("Enter A")
print(self)
print("Leave A")
class B(A):
def __init__(self):
print("Enter B")
print(self)
super(B, self).__init__()
print("Leave B")
class C(A):
def __init__(self):
print("Enter C")
print(self)
super(C, self).__init__()
print("Leave C")
class D(B, C):
def __init__(self):
print("Enter D")
print(self)
super(D, self).__init__()
print("Leave D")
d = D()
运行结果:
Enter D
<__main__.D object at 0x7fdb02618490>
Enter B
<__main__.D object at 0x7fdb02618490>
Enter C
<__main__.D object at 0x7fdb02618490>
Enter A
<__main__.D object at 0x7fdb02618490>
Leave A
Leave C
Leave B
Leave D
其中, D的MRO顺序为:
(
<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>
)
#super的本质如下:
def super(cls, inst):
mro = inst.__class__.mro()
return mro[mro.index(cls) + 1]
- 创建 D 类的对象 d 时,自动调用 D 类的初始化方法 __init()__,此时的 self 指向 D 类创建的实例对象 d;
- 调用原则:D->B->C->A
- 在调用到 B 时,首先输出 “Enter B”,但是运行到父类 A 的初始化方法时不立即调用,反而时转向广度优先级高的 C 类,因为 A 类对于 B 类来说是深度遍历。
另一个深入浅出的实例
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):
super().__init__()
self.sound = 'Squawk'
def sing(self):
print(self.sound)
在IDE中调用与输出:
sb = SongBird() # 实例化 SongBird 类为 sb
sb.sound # sb 的 sound 属性
'Squawk'
sb.sing # sb 的 方法 sing
<bound method SongBird.sing of <__main__.SongBird object at 0x000001E801D90D00>>
sb.sing() # 调用 sb 的方法 sing
Squawk
sb.hungry # sb 继承自类 Bird 的属性
True
sb.eat() # sb 继承自类 Bird 的方法 eat
Ahahahah
sb.hungry = False # 修改 sb的hungry的属性为False
sb.eat() # 调用sb.eat方法会变
No thanks!
MRO(method resolution order)总结
如果不同的父类中存在同名的方法, 子类对象在调用方法时, 会调用 哪一个父类中的方法呢?
如图B,C分别继承自A,并且D继承自B,C
---> B ---
test(self)
demo(self)
A --| |--> D
---> C ---
test(self)
demo(self)
提示:开发时,应该尽量避免这种容易产生混淆的情况!——如果父类之间存在同名的属性或者方法,应该尽量避免使用多继承
Python中的MRO——方法搜索顺序:
- 在搜索方法时,是按照mro的输出结果从左至右的顺序查找的
- 如果在当前类中找到方法,就直接执行,不再搜索
- 如果没有找到,就查找下一个类中是否有对应的方法,如果找到,就直接执行,不再搜索
- 如果找到最后一个类,还没有找到方法,程序报错
Python中针对类提供了一个内置属性mro可以查看方法搜索顺序
MRO是method resolution order,主要用于在多继承时判断方法、属性的调用路径
SongBird.__mro__
(
<class '__main__.SongBird'>,
<class '__main__.Bird'>,
<class 'object'>
)
D.__mro__
(
<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>
)
浅: 什么是__init__()
__init__(): Python 的构造方法类似 init() 这种初始化方法, 来初始化新创建对象的状态, 在一个对象被创建以后会立即调用,比如像实例化一个类:
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
f.somevar
42
# 我们会发现在初始化 FooBar 后得到了一个实例 f
# 实例化的 f 直接就能够调用 somevar 的值