0

What is the best practice for defining an equality operation to determine if a parent and child are effectively the same? Is there any good way to achieve this, or should I just avoid this desired behavior with a architecture change?

Parent Class

class Equal1(object):
    def __init__(self, value):
        self.value=value
    def get_value(self):
        return self.value
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__==other.__dict__
        return NotImplemented

Child Class

class Equal2(Equal1):
    def __init__(self, value):
        super().__init__(2 * value)
        self.other_values = ''

I want the following code to evaluate to True:

a = Equal1(2)
b = Equal2(1)
a == b
## True

It currently will not evaluate to True because the dictionaries are not identical, even if the functionality is the same.

One potential technique is to iterate through the smaller dictionary to check all of the key/value pairs to make sure they are the same as well as checking the local attributes using dir().

arewm
  • 649
  • 3
  • 12

1 Answers1

0

So you want to ignore the keys that only one of the objects has?

I would suggest replacing:

return self.__dict__==other.__dict__

with:

return all(self[k] == other[k] 
           for k in self.__dict__.keys() & other.__dict__.keys())

This makes the objects equal if all the keys, they both have, have equal values.

Dan D.
  • 73,243
  • 15
  • 104
  • 123