我是Python面向对象编程的新手,我很难理解super()函数(新样式类),尤其是涉及多重继承时.
例如,如果你有类似的东西:
class First(object):
def __init__(self):
print "first"
class Second(object):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
Run Code Online (Sandbox Code Playgroud)
我没有得到的是:Third()该类是否会继承构造函数方法?如果是,那么将使用super()运行哪一个?为什么?
如果你想运行另一个怎么办?我知道它与Python方法解析顺序(MRO)有关.
我试图了解python中的超级工作方式,并尝试了以下示例:
class A(object):
def __init__(self):
print "in A's init"
class B(object):
def __init__(self):
print "in B's init"
class C(A,B):
def __init__(self):
super(C,self).__init__()
print "In C"
if __name__=="__main__":
c=C()
Run Code Online (Sandbox Code Playgroud)
相当简单..我尝试了以下超级调用(在此处显示结果):
>>> super(B,c).__init__()
>>> super(B,c).__init__()
>>> super(A,c).__init__()
in B's init
>>> super(A,c).__init__()
in B's init
>>> super(A,c).__init__()
in B's init
>>> super(B,c).__init__()
>>> super(C,c).__init__()
in A's init
Run Code Online (Sandbox Code Playgroud)
我不明白为什么super(A,c).__init__()在B的init 中打印出它?