你不能使用super()
在类外部定义的函数中不带参数。这__class__
cell super()
只为 a 中定义的函数提供依赖class
身体。来自super()文档:
零参数形式仅适用于类定义内部,因为编译器会填写必要的详细信息以正确检索正在定义的类,以及访问普通方法的当前实例。
使用 2 参数形式,显式命名类:
def eq(obj, other):
if isinstance(other, str):
return obj.name.upper() == other.upper()
else:
return super(ClassYouPutThisOn, obj).__eq__(other)
ClassYouPutThisOn.__eq__ = eq
这要求您在猴子补丁中显式命名该类,从而使其重用性降低。
相反,您可以提供所需的__class__
cell manually通过嵌套eq
在另一个函数中__class__
作为本地名称:
def patch_eq(cls):
__class__ = cls # provide closure cell for super()
def eq(obj, other):
if isinstance(other, str):
return obj.name.upper() == other.upper()
else:
return super().__eq__(other)
cls.__eq__ = eq
super()
通过从调用框架中获取第一个本地名称(即传递到函数调用中的第一个参数,通常称为self
).
另请参阅为什么 Python 3.x 的 super() 如此神奇?
使用嵌套函数方法的演示:
>>> class Foo:
... name = 'bar'
... def __eq__(self, other):
... return False
...
>>> Foo() == 'Bar'
False
>>> Foo() == Foo()
False
>>> patch_eq(Foo)
>>> Foo() == 'Bar'
True
>>> Foo() == Foo()
False