[英]How does CPython keep track of the type of an object
我正在学习类,并想了解python如何跟踪对象的类型。 我可以想象,很容易分辨出int的类型是什么,因为它是内置类型
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)
python如何知道该对象的类型为p。 我了解,如果我想知道p1的类型,可以调用type(p1)
,但是我想知道该类型如何在内存中表示。 我认为这是从object
类继承的属性,在调用构造函数时会设置该属性,但是当我调用print(object.__dict__)
,没有类型属性。
内置目录将为您提供该对象的有效属性列表。
你的例子:
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)
然后
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']
我还不想将您与元类混淆,所以我将做一个简短的解释。 对象的__class__
属性返回该实例的类,在此您将其称为“类型”。
p1.__class__
返回此。
__main__.Point
__main__
是模块,而Point
是类。
但是,还有更多。 类也是对象,当您调用时
Point.__class__
它返回type
,并且type
是Python中的一个元类。 基本上,一个类的类是类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.