5.2. OOP Equality
5.2.1. Default Behavior
By default, all objects are not equal
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>> a == b
False
5.2.2. Equality Method
Both object are not equal
Mind, that the following implementation of __eq__
method is erroneous and should not be used.
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __eq__(self, other):
... return self.firstname == other.firstname \
... and self.lastname == other.lastname
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>> a == b
True
5.2.3. Equality Problem
Both object are not equal
Mind, that the following implementation of __eq__
method is erroneous and should not be used:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __eq__(self, other):
... return self.firstname == other.firstname \
... and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>> c = Admin('Mark', 'Watney')
>>> a == b
True
>>> a == c
True
5.2.4. Equality Solution
Both object are not equal
The following implementation of __eq__
method is correct and can be used:
>>> class User:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
...
... def __eq__(self, other):
... return self.__class__ is other.__class__ \
... and self.firstname == other.firstname \
... and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>> c = Admin('Mark', 'Watney')
>>> a == b
True
>>> a == c
False
5.2.5. Dataclasses
By default
eq=True
(if not specified)Objects of the same type are equal
Objects of different types are not equal
SetUp:
>>> from dataclasses import dataclass
By default instances of the same dataclass are equal:
>>> @dataclass
... class User:
... firstname: str
... lastname: str
>>>
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>>
>>> a == b
True
You can turn this behavior off by setting eq=False
:
>>> @dataclass(eq=False)
... class User:
... firstname: str
... lastname: str
>>>
>>> a = User('Mark', 'Watney')
>>> b = User('Mark', 'Watney')
>>>
>>> a == b
False