Teererai Marange
Teererai Marange

Reputation: 2132

How does CPython keep track of the type of an object

I am learning about classes and wanted to find out how python keeps track of what the type of an object is. I would imagine, that it is easy to tell what the type of an int is because it is a built in type

but now suppose, I have the following code: 
class Point:
    def __init__(self, x,y):
        self._x=x
        self._y=y

    def draw(self):
        print(self._x, self._y)
p1=Point(1,2)

How does python know that this object is of type p. I understand, that if I wanted to know the type of p1, I would call type(p1), but I was wondering how the type is represented in memory. I thought that it is an attribute inherited from the object class that gets set when I call the constructor, but when I call print(object.__dict__), there is no type attribute.

Upvotes: 1

Views: 46

Answers (2)

gunesevitan
gunesevitan

Reputation: 965

I don't want to confuse you with metaclasses yet, so I'll be giving a brief explanation. The __class__ attribute of an object returns the class of that instance, which you are referring "type" here.

p1.__class__

returns this.

__main__.Point

The __main__ is the module and Point is the class obviously.

However there is more than this. Classes are also objects and when you call

Point.__class__

It returns type, and type is a metaclass in Python. Basically the class of a class is type.

Upvotes: 1

Richard Rublev
Richard Rublev

Reputation: 8164

Builit-in dir will give you list of valid attributes for that object.

Your example:

class Point:
    def __init__(self, x,y):
        self._x=x
        self._y=y

    def draw(self):
        print(self._x, self._y)
p1=Point(1,2)

Then

print(dir(p1))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_x', '_y', 'draw']

Upvotes: 1

Related Questions