单继承
写法1(Python3+):
class Base():
def __init__(self, a):
self.a = a
print("Base init'ed")
class ChildA(Base):
def __init__(self):
print("ChildA init'ed")
super().__init__(123)
print(self.a)
写法2(Python2+, Python3+):
class Base():
def __init__(self, a):
self.a = a
print("Base init'ed")
class ChildA(Base):
def __init__(self):
print("ChildA init'ed")
super(ChildA, self).__init__(123)
print(self.a)
写法3(Python2+, Python3+):
class Base():
def __init__(self, a):
self.a = a
print("Base init'ed")
class ChildA(Base):
def __init__(self):
print("ChildA init'ed")
Base.__init__(self, 123)
print(self.a)
Output:
>>> ChildA()
ChildA init'ed
Base init'ed
123
多继承
写法1:
class First():
def __init__(self):
print('1')
super().__init__()
print("first")
class Second():
def __init__(self):
print('2')
super().__init__()
print("second")
class Third(First, Second):
def __init__(self):
super().__init__()
print("third")
写法2:
class First():
def __init__(self):
print('1')
super(First, self).__init__()
print("first")
class Second():
def __init__(self):
print('2')
super(Second, self).__init__()
print("second")
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print("third")
写法3:
class First():
def __init__(self):
print('1')
super(First, self).__init__()
print("first")
class Second():
def __init__(self):
print('2')
super(Second, self).__init__()
print("second")
class Third(First, Second):
def __init__(self):
First.__init__(self)
print("third")
Output:
>>> Third()
1
2
second
first
third
注意super方法的返回:
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
The object-or-type determines the method resolution order to be searched. The search starts from the class right after the type.
For example, if mro of object-or-type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.
所以如果First类中没有super方法则会导致输出为:
1
first
third
这是由于根据方法解析路径MRO,在搜索到First后就停止了。
查看MRO:
# 执行方法
>>> Third.mro()
(__main__.Third, __main__.First, __main__.Second, object)
# 获取属性
>>> Third.__mro__
(__main__.Third, __main__.First, __main__.Second, object)
参考:
https://docs.python.org/3/library/functions.html#super
https://www.cnblogs.com/crazyrunning/p/7095014.html