Exploring Dunder Methods in Action
Right now if I save with Control + S and F5 to run, we don’t get any output. So the class is being defined without any errors. So let’s instantiate a couple instances of this class. Let’s look at
origin = Point() we’ll call it
0, 0, and we’ll say
target and we’ll use the same code to instantiate it.
So to us, to humans, this seems like they’re both the same point, right? They’re both pointing at the same point in space:
0, 0. But if we try and run
origin == target, and we Control + S to save and F5 to run, you’ll see that that gives us
And that’s because
target are two different instances of the class. They have different memory addresses. They live separately in memory in Python, and therefore if you just compare them directly, they are not equal to each other, even though to us it seems like they are the same because the values within them, the
0, 0, conceptually for humans point to the same thing, so they should be equal.
If we now Control + S to save this and F5 to run that, we’ll see that it’s
True. And now this is the check that we really want to make, whether
origin.x is the same as
origin.y is the same as
target.y, but there’s quite a lot of stuff to type out and to remember every time we want to compare a point. Maybe we want to compare lots of points in our program.
So ideally we just want the original version,
origin == target, without any referencing of
.y just to work. We could make a custom method, but we can use another special dunder method called
def __eq__(), of course stands for equals.
So if this is actually true, then it will return
True, and if it’s not true, then it’ll return
False. So the way this works is that whenever you have an instance of
Point and you use the
== (equals to) operator, it will take the object on the left, and that will be assigned to
self.y—and then the object on the right will be assigned to
So now when we run this code, Control + S, F5, you’ll get
True. So this is just one of the features that makes Python really great for object-oriented programming because you have a whole range of these special dunder methods where you can override this operator, the
== two operator, but also addition, subtraction, multiplication, greater than, less than—you can define the behavior for all of these, so then you can use operators with your objects and not have to define custom methods like
origin.is_equal_to() and then have
target, which you can do, but somehow just being able to use the operators seems neater.
Become a Member to join the conversation.