你不能。该
super()调用需要知道该方法属于哪个类,以在基类中搜索被覆盖的方法。
如果您在传递
self.__class__(或更好,
type(self))则
super()给出 错误的 出发点,以寻找方法,并最终调用_再次它自己的方法_ 。
在构成方法解析顺序序列的类列表中,将其视为指针。如果传入,
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()
演示:
>>> Subclass().method()subclass of derivedderivedderivedderived<... *many* lines removed ...> File "<stdin>", line 4, in method File "<stdin>", line 4, in method File "<stdin>", line 4, in methodRuntimeError: maximum recursion depth exceeded while calling a Python object
因为
type(self)是
Subclass, 没有
Derived在
Derived.method()。
在这个例子中,MRO为
Subclass是
[Subclass, Derived,base],而
super()需要知道从哪里开始寻找任何替代的方法。通过使用
type(self)它告诉它从开始
Subclass,所以它将
Derived.method()在我们开始的地方找到下一个。



