在看python高级编程这本书的时候,在讲到super的时候,产生了一些疑惑,super在python中的用法跟其他的语言有一些不一样的地方,在网上找了一些资料,发现基本上很少有文章能把我的疑惑讲明白,其中这篇文章最有价值的地方是它讲解了我们平时对super的正确使用方法。
首先,我们来看一个节目:
[En]
First, let’s take a look at a program:
class A:
def __init__(self):
print("A", end=" ")
super().__init__()
class E:
def __init__(self):
print("E", end=" ")
super().__init__()
class B(E):
def __init__(self):
print("B", end=" ")
super().__init__()
class D:
def __init__(self):
print("D", end=" ")
super().__init__()
class C(A, B, D):
def __init__(self):
print("C", end=" ")
A.__init__(self)
D.__init__(self)
B.__init__(self)
print("MRO:", [x.__name__ for x in C.__mro__])
print(C())
本程序的打印结果为:
[En]
The printed result of this program is:
MRO: ['C', 'A', 'B', 'E', 'D', 'object']
C A B E D D B E D <__main__.c object at 0x1040340b8>
</__main__.c>
这段程序可以简单演示super()的用法,比较简单的概念是__mro__,它告诉我们某个类的继承链信息,生成这个链的原则有两条:
- 在继承关系中,所有子类都在父类之前
[En]
* in an inheritance relationship, all subclasses precede the parent class
- 如果出现冲突,则按照其__base__排序
要理解上面程序的打印结果,只需要知道Super()实际上等同于Super(cls,self),答案就很清楚了。
[En]
To understand the printed result of the above program, you only need to know that super () is actually equivalent to super (cls, self), and the answer is clear.
当执行 A.__init__(self)
这行代码的时候,self指向了c实例对象,然后打印出A,当调用 super().__init__()
这行代码的时候,实际相当于 super(A, self).__init__()
的调用, super(A, self)
的会在self.__mro__中查找排在A后边的类,这样就实现了继承链的调用了。
事实上,在这一点上,我们基本上可以猜测出Super()的实现原理,虽然看起来它没有传入参数,但实际上,如果我们更改参数,我们会发现一个不同的父类。
[En]
In fact, at this point, we can basically guess the implementation principle of super (), although it looks as if it did not pass in parameters, but in fact, if we change the parameters, we will find a different parent class.
让我们稍微更改一下上面代码中的AN:
[En]
Let’s change the An in the above code slightly:
class A:
def __init__(self):
print("A", end=" ")
super(D, self).__init__()
那么在这里 super(D, self)
获取的就是object了,因此打印结果是:
MRO: ['C', 'A', 'B', 'E', 'D', 'object']
C A D B E D
Original: https://www.cnblogs.com/machao/p/8656329.html
Author: 马在路上
Title: python中super()的一些用法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6666/
转载文章受原作者版权保护。转载请注明原作者出处!