What argument ‘isinstance’ takes on declaring ‘k’ object?

Tags: , ,



class Point:
    def __init__(self, x_or_obj = 0, y = 0):
        if isinstance(x_or_obj, Point):
            self.x = x_or_obj.x
            self.y = x_or_obj.y
        else:
            self.x = x_or_obj
            self.y = y

m = Point(1,2)
k = Point(m)

So I have difficulties with understanding why isinstance evaluating True in this code. I see it as int is checking against class, which makes no sense to me.

Answer

Looking at this article about isinstance:

The isinstance() function returns True if the specified object is of the specified type, otherwise False.

In m‘s definition:

m = Point(1,2)

You’re passing 1 as the value of x_or_obj. 1 is an integer, not a Point, therefore it evaluates to False.

However, in k‘s definition:

k = Point(m)

you’re passing m as the value of x_or_obj. You earlier defined m as type Point, so isinstance evaluates to True.



Source: stackoverflow