【问题标题】:Relationship between objects and classes in Python 3Python 3 中对象和类之间的关系
【发布时间】:2011-06-30 08:32:23
【问题描述】:

我以为我意识到了这种关系:在 Python 中,一切都是对象,每个对象都有一个类型。但是课程呢?类是对象的蓝图,对象是类的实例。但我读过in an article,在 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 本身就是一个对象。我不明白这。我无法想象类是对象。

【问题讨论】:

    标签: python class oop object types


    【解决方案1】:

    在 Python 中可以命名的一切都是对象——包括函数、类和元类。每个对象都有一个关联的 typeclass(这是同一事物的两个名称——“type”和“class”在 Python 3 中是相同的)。类型本身又是一个对象,并且有一个关联的类型。类型的类型称为metaclass(当然,它同样可以称为metatype,但不使用后一个词)。您可以使用type() 来确定对象的类型。如果你迭代地查询一个对象的类型,它的类型等等,你总是会在某个时候得到type的类型,通常是经过两个步骤:

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

    另一个例子,使用“元元类”:

    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 类型并不矛盾。

    【讨论】:

    • 我想我明白了:类和对象在python中是两个平行的东西:每个对象都有它的类(类型),每个类都是一个对象
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-06-20
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多