不,你不能。 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 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
因为type(self) 是Subclass,不是 Derived,在Derived.method()。
在示例中,Subclass 的 MRO 是 [Subclass, Derived, Base],super() 需要知道从哪里开始搜索任何被覆盖的方法。通过使用type(self),您可以告诉它从Subclass 开始,所以它会在下一个找到Derived.method(),这就是我们开始的地方。