你不能。这super()
call 需要知道该方法属于哪个类,以便在基类中搜索重写的方法。
如果你通过self.__class__
(或者更好的是,type(self)
) then super()
被赋予wrong搜索方法的起点,最终会调用又是自己的方法.
将其视为形成方法解析顺序序列的类列表中的指针。如果你通过type(self)
那么指针将指向任何子类而不是原始起点。
以下代码会导致无限递归错误:
class Base(object):
def method(self):
print 'original'
class Derived(Base):
def method(self):
print 'derived'
super(type(self), self).method()
class Subclass(Derived):
def method(self):
print 'subclass of derived'
super(Subclass, self).method()
Demo:
>>> Subclass().method()
subclass of derived
derived
derived
derived
<... *many* lines removed ...>
File "<stdin>", line 4, in method
File "<stdin>", line 4, in method
File "<stdin>", line 4, in method
RuntimeError: maximum recursion depth exceeded while calling a Python object
because type(self)
is Subclass
, not Derived
, in Derived.method()
.
在示例中,MROSubclass
is [Subclass, Derived, Base]
, and super()
需要知道从哪里开始搜索任何被重写的方法。通过使用type(self)
你告诉它开始于Subclass
,所以它会发现Derived.method()
接下来,这就是我们开始的地方。