__eq__メソッド は等価の条件を定める
class Person: 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 return self.firstname == other.firstname and \ self.lastname == other.lastname and \ self.email == other.email def __ne__(self, other): return not self.__eq__(other) mike = Person('Mike', 'Peter', 'mike@gmail.com') peter = Person('Mike', 'Peter', 'mike@gmail.com') print(mike) print(peter) print(mike == peter)
eqの他にも、lt, ne, le, gt, geなどがある。
class Item(object): def __init__(self, price): self.price = price def __eq__(self, other): if not isinstance(other, Item): return NotImplemented return self.price == other.price def __lt__(self, other): if not isinstance(other, Item): return NotImplemented return self.price < other.price def __ne__(self, other): return not self.__eq__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other)