首页 > 解决方案 > 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.

标签: pythonclassoop

解决方案


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']

推荐阅读