Auto-translation used

📚 SDE Best Practices: Behavior vs implementation

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

Comments 0

Login to leave a comment