If you want to apply the comparison operator to the defined class, implement the rich comparison method. Considering a class that represents a person as an example, it looks like this:
class Person(object):
def __init__(self, firstname, lastname, email):
self.firstname = firstname
self.lastname = lastname
self.email= email
def __eq__(self, other):
if other is None or not isinstance(other, Person): return False
#The following is troublesome
return self.firstname == other.firstname and
self.lastname == other.lastname and
self.email == other.email
def __ne__(self, other):
return not self.__eq__(other)
To be honest, it's annoying to write self.xxx == other.xxx and ... every time you define a class. So I will use the dict method inherited from the base class.
class Person(object):
def __init__(self, firstname, lastname, email):
self.firstname = firstname
self.lastname = lastname
self.email= email
def __eq__(self, other):
# isinstance(other, Person)Remove
if other is None or type(self) != type(other): return False
# __dict__Compare attributes using methods
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
Now you can compare two objects in a generic way without having to write the attribute name. assertEquals also passes with a margin. It's assumed that the attribute has a eq method.
Recommended Posts