what does super really do in python
我刚刚阅读了gvr的方法解析顺序,但是我想知道下面的语句在python的super中是否正确(我同意这一点),这很漂亮,但是您不能使用它。所以
One big problem with 'super' is that it sounds like it will cause the
superclass's copy of the method to be called. This is simply not the
case, it causes the next method in the MRO to be called (...)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class A(object): def __init__(self): #super(A, self).__init__() print 'init A' class B(object): def __init__(self): print 'init B' class C(A, B): def __init__(self): super(C, self).__init__() print 'init C' c = C() |
给予
1 2 | init A init C |
同时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class A(object): def __init__(self): super(A, self).__init__() print 'init A' class B(object): def __init__(self): print 'init B' class C(A, B): def __init__(self): super(C, self).__init__() print 'init C' c = C() |
给予
1 2 3 | init B init A init C |
两种情况下的预期结果…在第一种情况下,C调用一个(MRO中的下一个类),该类打印"init a"并返回,因此流返回到C,该C打印"init c"并返回。匹配您的输出。
在第二种情况下,c调用a(mro中的next),后者调用b(mro中的a旁边),后者打印"init b"并返回,因此流返回到a,后者打印"init a"并返回到c,后者打印"init c"。