Checking Equivalence Between Objects
00:00 In this lesson, you’re going to find out how to check equivalence between objects. Objects behave slightly differently from normal values in that you can’t compare them the same way you would, say, a number.
There is a built-in function called
isinstance(), which is the recommended way to check between objects to check if they’re the same type, but you can also make use of the built-in
type() function as well.
So say you had two points,
target, and say that they were actually equivalent in the sense that you and I know from looking at these points that they represent the same point in space, the
0, 0 origin point.
And this is true also of
is. This is because objects or instances behave very differently. They actually live at different memory addresses, as you’ve seen at the start of the course. They are separate objects.
Even though they have the same instance attributes doesn’t mean they are the same or can be compared straight away. There are some things that you can check right off the bat using
If you call
isinstance(), which is a inbuilt function—you don’t need to import it or anything—the first argument is the object that you want to test, and you want to check if it’s an instance of the second argument, a
You can define all of these behaviors individually, but that’s going to come in a later lesson with something called special methods, or dunder methods. You do have a couple tools right off the bat, which is
And you can also check what the type of
target is, and this will give you this notation here that says it is a member of the
Point class. But as you can see, this type of output isn’t maybe as clear as just checking
isinstance(), where you can put the name of the class, and it’s much easier to work with. If you wanted to check whether
target had the same values and so that they represented the same point, without dunder methods, what you’d have to do for now is to go
origin.x == target.x and origin.y == target.y, and that will give you
True because they both have
0, 0 as their point.
Become a Member to join the conversation.