是否可以在运行时重载操作符?我尝试了以下代码示例:
class A():
pass
a = A()
a.__eq__ = lambda self, other: False
a == a # this should return False since the __eq__-method should be overloaded but it returns
# True like object.__eq__ would
a.__eq__(a, a) # this returns False just as expected
为什么这个代码不起作用?是否有可能实现理想的行为?
答案 0 :(得分:2)
在类上查找Magic / double下划线方法,而不是在实例上查找。所以你需要覆盖类的方法,而不是实例。有两种方法可以做到这一点。
直接分配给班级:
class A:
pass
a = A()
A.__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a)) # You're already passing in self by calling it as an instance method, so you only pass in the other one.
或者,如果您只有实例并且使用的是3.x,则可以执行以下操作:
class A:
pass
a = A()
type(a).__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a))