请参阅PEP3135.必须将类显式命名为全局类,也很容易出现与您发现的重新绑定问题相同的问题。本身:class Foo(Bar):
def baz(self):
return super(Foo, self).baz() + 42
Spam = Foo
Foo = something_else()
instance = Spam() # liable to blow up
同样的情况也适用于使用类装饰器,其中装饰器返回一个新对象,该对象重新绑定类名:@class_decorator_returning_new_class
class Foo(Bar):
def baz(self):
# Now `Foo` is a *different class*
return super(Foo, self).baz() + 42
super()通过赋予您对原始类对象的访问权限,很好地避免了这些问题。
方法:>>> super_ = super
>>> class A(object):
... def x(self):
... print("No flipping")
...
>>> class B(A):
... def x(self):
... __class__ # just referencing it is enough
... super_().x()
...
>>> B().x()
No flipping