【发布时间】:2017-10-02 09:34:29
【问题描述】:
我正在修补类的__eq__ 方法。我发现以下工作:
def eq(obj, other):
if isinstance(other, str):
return obj.name.upper() == other.upper()
else:
return object.__eq__(obj, other)
这不起作用:
def eq(obj, other):
if isinstance(other, str):
return obj.name.upper() == other.upper()
else:
return super().__eq__(other)
这有时有效,但有时会引发错误:
def eq(obj, other):
if isinstance(other, str):
return obj.name.upper() == other.upper()
else:
return super().__eq__(self, other)
错误:
<ipython-input-128-91287536205d> in eq(obj, other)
3 return obj.name.upper() == other.upper()
4 else:
----> 5 return super().__eq__(self, other)
6
7
RuntimeError: super(): __class__ cell not found
你能解释一下这里发生了什么吗?如何正确地将object 替换为super()?
【问题讨论】:
-
除了缩进之外,您的“不起作用”和“有时起作用”示例之间没有区别。只要没有到达
else分支,两者都只是“有时”工作。 -
注意
super(...).__eq__是一个绑定方法,所以第一个参数(通常命名为self)会自动从第二个参数传入super(cls, instance)。你只需要传入other:super(...).__eq__(other)。 -
我在类之外创建
__new__时遇到了这个错误(动态地,出于测试目的,在实际代码中你真的不需要这种魔法),使用2-参数@ 987654335@ 像super(metaclass, cls).__new__(cls)一样调用metaclass几乎总是只是type解决了这个问题
标签: python python-3.x super overloading monkeypatching