Environment: Python 2.7 (It just might have something to do with this.)
First I understand the '==' is implemented as following (source):
- if
type(b)
is a new-style class,type(b)
is a subclass oftype(a)
type(b)
has overridden__eq__
then the result is
b.__eq__(a)
- If
type(a)
has overridden__eq__
(that is,type(a).__eq__
isn'tobject.__eq__
)then the result is
a.__eq__(b)
- If
type(b)
has overridden__eq__
then the result is
b.__eq__(a)
.
If none of the above are the case, repeats the process above, but looking for
__cmp__
. If it exists, the objects are equal if it returns zero.As a final fallback, Python calls
object.__eq__(a, b)
, which is just testing if a and b are the same object.
.
Now I want to override __eq__
of an object, but falls back to the mechanism above when object has no custom __eq__
defined. How to achieve this?
I can't just save the original __eq__
method because '==' actually involves a complex mechanism described above.
Example Code (with target not achieved):
class A(object):
def __eq__(self, other):
try:
self.___eq___
return self.___eq___(other)
except AttributeError:
# trying to save default behaviour (Goal)
def custom_eq_bound_method(self, other):
return True
# overriding __eq__
a1 = A()
a1.___eq___ = MethodType(custom_eq_bound_method, a1, A)
# not overriding __eq__
a2 = A()
# comparing a1 == a2 in business logic....