Публикация была переведена автоматически. Исходный язык: Английский
На курсе промышленной разработки на Python задают много крутых вопросов. Продолжаю делиться ответами на некоторые из них.
❓Вопрос: должен ли класс реализовывать метод __eq__?
Рекомендую взять в практику тезис:
следует тестировать поведение, а не реализацию
Рассмотрим реализацию класса Point с атрибутами x и y:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
Создадим объекты класса a и b:
a = Point(x=1, y=2)
b = Point(x=1, y=2)
Вопрос: как вы будете проверять, что объекты равны?
Логичный ответ:
a == b
// это была проверка поведения
Вы не будете проверять:
a.x == b.x and a.y == b.y
// это была бы проверка реализации
Тесты вашего приложения должны быть наполнены проверкой поведения, а не реализации. В этом случае код будет гораздо легче поддерживать и обновлять.
Вернемся к оригинальному вопросу: если не реализовать метод __eq__, то будут объекты a и b будут неравны. Почему? Какое поведение __eq__ по умолчанию?
#work #study
There are a lot of cool questions being asked in the Python industrial development course. I continue to share answers to some of them.
Question: Should the class implement the __eq__ method?
I recommend putting the thesis into practice:
the behavior should be tested, not the implementation
Consider the implementation of the Point class with the attributes x and y:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
Let's create objects of class a and b:
a = Point(x=1, y=2)
b = Point(x=1, y=2)
Question: How will you check that the objects are equal?
The logical answer:
a == b
// it was a behavior check
You will not check:
a.x == b.x and a.y == b.y
// this would be an implementation check
Your application's tests should be filled with behavior testing, not implementation testing. In this case, the code will be much easier to maintain and update.
Let's return to the original question: if you do not implement the __eq__ method, then objects a and b will be unequal. Why? What is the default behavior of __eq__?
#work #study