Reputation: 183
Is it possible to overload a operator at runtime? I tried the following code example:
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
Why won't this code work? Is it possible to achieve the desired behavior?
Upvotes: 1
Views: 200
Reputation: 9986
Magic/double underscore methods are looked up on the class, not on the instance. So you need to override the class's method, not the instance. There are two ways to do this.
Either directly assign to the class as such:
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.
Or if you only have the instance and you're using 3.x, you can do:
class A:
pass
a = A()
type(a).__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a))
Upvotes: 2