Overload operator at runtime
<p>Is it possible to overload a operator at runtime? I tried the following code example:</p>

<pre><code>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
</code></pre>

<p>Why won't this code work? Is it possible to achieve the desired behavior?</p>

<p>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.</p>

<p>Either directly assign to the class as such:</p>

<pre><code>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.
</code></pre>

<p>Or if you only have the instance and you're using 3.x, you can do:</p>

<pre><code>class A:
    pass

a = A()
type(a).__eq__ = lambda self, other: False
print(a == a)
print(a.__eq__(a))
</code></pre>

python operator-overloading