1

for example, I have this class and two instances of it:

class A:
    def __init__(self, version):
        self.version = version

a1 = A('1.0')
a2 = A('1.0')

because there is no direct way to compare a1 and a2. I override the __eq__ method of both instances using MethodType.

def compare(self, other):
    if not isinstance(other, self.__class__):
        raise TypeError
    return self.version == other.version

a1.__eq__ = MethodType(compare, a1, a1.__class__)
a2.__eq__ = MethodType(compare, a2, a2.__class__)

However, after all these effort, a1 == a2 still returns False.

After some research, I get that in order for == to be overridden, one must override the __eq__ method for the class, not the instance.

One of the reasons why I don't do this at class level is that doing so would pollute the class, I only produce instances using some functions(not sub-classes) and adding attributes dynamically for comparison.

I want to know if there is a way to override == at instance level without change the class.

Sajuuk
  • 2,667
  • 3
  • 22
  • 34
  • this may help: https://stackoverflow.com/questions/47878846/monkey-patching-eq-in-python – hiro protagonist May 14 '19 at 09:47
  • Why not to override at the class level? – balderman May 14 '19 at 09:49
  • @balderman updated my question for your question. – Sajuuk May 14 '19 at 09:54
  • 1
    @Sajuuk I read you addition to the post and I still dont understand.. If the natural way to tell if 2 instances of A are the same (a1 == a2) is to compare their versions it looks very natural (in my eyes) to implement `__eq__` – balderman May 14 '19 at 09:57
  • 1
    Possible duplicate of [Overriding special methods on an instance](https://stackoverflow.com/questions/10376604/overriding-special-methods-on-an-instance) – quamrana May 14 '19 at 10:05
  • @balderman maybe I had gone stray, what I did is having mulitple functions producing instances of the same class but adding different attributes correspondingly, thus the difference. I want to make sure instances produced by same function test equal. – Sajuuk May 14 '19 at 10:44
  • @quamrana that question provided some insight indeed. looks like I have to override `__eq__` at class level to capture method bound to instance.. – Sajuuk May 14 '19 at 10:56
  • Yes, once you have written `__eq__` at a class level to redirect to an instance method, that instance method can be overridden at any time after an instance has been created, but before `==` is used. – quamrana May 14 '19 at 13:01
  • @quamrana yeah and that led to another problem is how can I save original `__eq__` as a fallback.. which is 'equally' tricky.. – Sajuuk May 15 '19 at 02:01
  • You need to ask another question about this. Sounds like an interesting problem. – quamrana May 15 '19 at 07:38
  • @quamrana already done yesterday: https://stackoverflow.com/questions/56129685/how-to-access-a-method-inside-a-class – Sajuuk May 15 '19 at 09:40

0 Answers0