python - 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.
解决方案
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']
推荐阅读
- javascript - 如何创建自定义过滤器以在 Vue.js 中的多选 v-autocomplete 顶部排列所选项目
- javascript - 如何使用组过滤 mongo db 中的数据?
- haskell - 如何使用 Parsec 解析三元表达式?
- swift - 使用 didSelect 方法在 viewDidLoad 之后在单元格中显示图像
- python - 烧瓶python中的特殊字符问题
- powershell - 调用命令 InDisconnectedSession SessionOption 和 IdleTimeout 一班
- java - 哈希字符串可排序 - 大数据
- javascript - 将正则表达式应用于 redux-form 的 Field 组件中的 TextField 组件
- javascript - React:使用 createRef 从输入中获取数据
- r - `r_make()` 和 `make()` 在 r-drake 中不一致