The two-argument form is only needed in Python 2. The reason is that self.__class__
always refers to the "leaf" class in the inheritance tree -- that is, the most specific class of the object -- but when you call super
you need to tell it which implementation is currently being invoked, so it can invoke the next one in the inheritance tree.
Suppose you have:
class A(object):
def foo(self):
pass
class B(A):
def foo(self):
super(self.__class__, self).foo()
class C(B):
def foo(self):
super(self.__class__, self).foo()
c = C()
Note that c.__class__
is C
, always. Now think about what happens if you call c.foo()
.
When you call super(self.__class__, self)
in a method of C, it will be like calling super(C, self)
, which means "call the version of this method inherited by C". That will call B.foo
, which is fine. But when you call super(self.__class__, self)
from B, it's still like calling super(C, self)
, because it's the same self
, so self.__class__
is still C
. The result is that the call in B will again call B.foo
and an infinite recursion occurs.
Of course, what you really want is to be able to call super(classThatDefinedTheImplementationThatIsCurrentlyExecuting, self)
, and that is effectively what the Python 3 super()
does.
In Python 3, you can just do super().foo()
and it does the right thing. It's not clear to me what you mean about super(self)
being a shortcut. In Python 2, it doesn't work for the reason I described above. In Python 3, it would be a "longcut" because you can just use plain super()
instead.
The super(type)
and super(type1, type2)
uses might still be needed occasionally in Python 3, but those were always more esoteric usages for unusual situations.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…