Python 3中对象与类之间的关系 [英] Relationship between objects and classes in Python 3

查看:67
本文介绍了Python 3中对象与类之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我意识到了这种关系:在Python中,所有事物都是一个对象,而每个对象都有一个类型.但是上课呢?类是对象的蓝图,而对象是类的实例.但是我已经阅读在文章中在Python中,类本身就是对象.我认为没有它的蓝图-它的类就不可能存在一个对象.但是,如果class是一个对象,那么它如何存在?

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'>,)

那么, object 类是每个对象的蓝图吗?

So, the class object is the blueprint of every object?

>>> type(str)
<class 'type'>
>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>

那么, type 类是其他所有类型的蓝图吗?

So, class type is blueprint of every other type?

但是 type 本身就是一个对象.我无法理解这.我无法想象类是对象.

But type is an object itself. I cannot understand this. I cannot imagine that classes are objects.

推荐答案

在Python中可以命名的所有对象都是对象-包括函数,类和元类.每个对象都有一个关联的 type class (这是同一事物的两个名称-Python 3中的"type"和"class"相同).类型本身又是一个对象,并且本身具有关联的类型.类型的类型称为 metaclass (当然,也可以将其称为 metatype ,但不使用后者).您可以使用 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 type type at some point, usually after two steps:

type(3)    # --> int
type(int)  # --> type
type(type) # --> type

另一个示例,使用"meta-metaclasses":

Another example, using "meta-metaclasses":

class A(type):
    pass
class B(type, metaclass=A):
    pass
class C(metaclass=B):
    pass
c = C()

type(c)    # --> C
type(C)    # --> B
type(B)    # --> A
type(A)    # --> type
type(type) # --> type

type 本身就是 type 类型,这并不矛盾.

There is no contradiction in type being itself of type type.

这篇关于Python 3中对象与类之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆