Сравнение объектов
В этом разделе мы изучим магические методы, используемые для сравнения объектов в Python. Эти методы позволяют определить пользовательскую логику сравнения для объектов вашего класса.
__eq__
Метод __eq__ используется для определения, равны ли два объекта. Он вызывается оператором ==.
#... (предыдущий код в person.py)
def __eq__(self, other: "Person") -> bool:
"""
Compare two Person objects for equality.
:param other: The other Person object to compare with.
:return: True if both objects have the same name and age, False otherwise.
"""
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False
__ne__
Метод __ne__ используется для определения, не равны ли два объекта. Он вызывается оператором !=.
#... (предыдущий код в person.py)
def __ne__(self, other: "Person") -> bool:
"""
Compare two Person objects for inequality.
:param other: The other Person object to compare with.
:return: True if the objects have different names or ages, False otherwise.
"""
return not self.__eq__(other)
__lt__
Метод __lt__ используется для определения, меньше ли один объект другого. Он вызывается оператором <.
#... (предыдущий код в person.py)
def __lt__(self, other: "Person") -> bool:
"""
Compare two Person objects to see if one is less than the other based on age.
:param other: The other Person object to compare with.
:return: True if the current object's age is less than the other object's age, False otherwise.
"""
if isinstance(other, Person):
return self.age < other.age
return NotImplemented
__le__
Метод __le__ используется для определения, меньше или равен ли один объект другому. Он вызывается оператором <=.
#... (предыдущий код в person.py)
def __le__(self, other: "Person") -> bool:
"""
Compare two Person objects to see if one is less than or equal to the other based on age.
:param other: The other Person object to compare with.
:return: True if the current object's age is less than or equal to the other object's age, False otherwise.
"""
if isinstance(other, Person):
return self.age <= other.age
return NotImplemented
__gt__
Метод __gt__ используется для определения, больше ли один объект другого. Он вызывается оператором >.
#... (предыдущий код в person.py)
def __gt__(self, other: "Person") -> bool:
"""
Compare two Person objects to see if one is greater than the other based on age.
:param other: The other Person object to compare with.
:return: True if the current object's age is greater than the other object's age, False otherwise.
"""
if isinstance(other, Person):
return self.age > other.age
return NotImplemented
__ge__
Метод __ge__ используется для определения, больше или равен ли один объект другому. Он вызывается оператором >=.
#... (предыдущий код в person.py)
def __ge__(self, other: "Person") -> bool:
"""
Compare two Person objects to see if one is greater than or equal to the other based on age.
:param other: The other Person object to compare with.
:return: True if the current object's age is greater than or equal to the other object's age, False otherwise.
"""
if isinstance(other, Person):
return self.age >= other.age
return NotImplemented
Пример: Использование магических методов сравнения объектов
Теперь, когда мы определили магические методы сравнения объектов для нашего класса Person, посмотрим, как они работают в compare_example.py:
from person import Person
## Create two Person objects
p1 = Person("Alice", 30)
p2 = Person("Bob", 35)
## Use the __eq__ and __ne__ methods
print(p1 == p2) ## Output: False
print(p1!= p2) ## Output: True
## Use the __lt__, __le__, __gt__, and __ge__ methods
print(p1 < p2) ## Output: True
print(p1 <= p2) ## Output: True
print(p1 > p2) ## Output: False
print(p1 >= p2) ## Output: False
Затем введите следующую команду в терминале для выполнения скрипта.
python compare_example.py