Python 3 中对象和类之间的关系
我以为我意识到了这种关系:在Python中一切都是对象,并且每个对象都有一个类型。但是课程呢?类是对象的蓝图,对象是类的实例。但我在Python中读过一篇文章 ,类本身就是对象。我认为一个对象如果没有它的蓝图——它的类就不可能存在。但是,如果类是一个对象,那么它如何存在呢?
>>> type.__bases__
(<class 'object'>,)
>>> int.__bases__
(<class 'object'>,)
>>> str.__bases__
(<class 'object'>,)
那么,object
类是每个对象的蓝图吗?
>>> type(str)
<class 'type'>
>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>
那么,类 type
是所有其他类型的蓝图吗?
但 type
本身就是一个对象。我无法理解这一点。我无法想象类是对象。
I thought that I realized this relationship: In Python everything is an object, and every object has a type. But what about classes? A class is a blueprint of an object, and an object is instance of a class. But I have read in an article that in Python, classes are themselves objects. I thought that an object cannot exist without its blueprint - its class. But, if class is an object, how it can exist?
>>> type.__bases__
(<class 'object'>,)
>>> int.__bases__
(<class 'object'>,)
>>> str.__bases__
(<class 'object'>,)
So, the class object
is the blueprint of every object?
>>> type(str)
<class 'type'>
>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>
So, class type
is blueprint of every other type?
But type
is an object itself. I cannot understand this. I cannot imagine that classes are objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Python 中,所有可以命名的东西都是对象——包括函数、类和元类。每个对象都有一个关联的类型或类(这是同一事物的两个名称——“类型”和“类”在Python 3中是相同的)。该类型本身又是一个对象,并且它本身有一个关联的类型。类型的类型称为元类(当然,它同样可以称为元类型,但不使用后一个词)。您可以使用
type()
来确定对象的类型。如果你迭代地查询一个对象的类型、其类型的类型等等,你总是会在某个时刻得到类型type
,通常是在两个步骤之后:另一个例子,使用“meta -metaclasses":
type
本身就是type
类型,这并不矛盾。Everything that can be given a name in Python is an object - including functions, classes and metaclasses. Every object has an associated type or class (these are two names for the same thing -- "type" and "class" are the same in Python 3). The type itself is an object again, and has itself an associated type. The type of a type is called a metaclass (of course, it could equally well be called a metatype, but the latter word is not used). You can use
type()
to determine the type of an object. If you iteratively query the type of an object, the type of its type and so on, you will always end up with the typetype
at some point, usually after two steps:Another example, using "meta-metaclasses":
There is no contradiction in
type
being itself of typetype
.