Python3 中的子类类型与对象

Subclassing type vs object in Python3

我一直在阅读有关 metaclasses 的内容,但当涉及到 typeobject classes.

时,我迷路了

我知道它们位于层次结构的顶部,并且是用 C 代码实现的。 我也明白 type 继承自 objectobjecttype.

的一个实例

在我在 SO 上发现的 answers 之一中,有人说 - 关于 object-type 关系 - 那:

This kind of mutual inheritance is not normally possible, but that's the way it is for these fundamental types in Python: they break the rules.

我的问题是为什么要这样实现,这样实现的目的是什么? solve/what 这种设计的好处是什么问题?难道不能只是 type 或只是 object class 位于每个 class 继承自的层次结构的顶部吗?

最后,object 的 subclassing 和 type 的 subclassing 之间有什么区别吗?其他?

class Foo(object):
    pass

class Foo(type):
    pass

在Python中一切皆对象。每个对象都有一个类型。事实上,一个对象的类型也是一个对象,因此也必须有它自己的类型。类型有一种特殊类型,称为 type。这(与任何其他类型一样)是一个对象,因此是 object.

的一个实例

每个对象都是object的实例,包括任何对象的任何类型。所以 int 是一个对象,str 也是一个对象,还有更明显的例子,例如 1'asd'。您可以引用或分配给 Python 中的变量的任何内容都是 object.

的实例

因为 object 是一个类型,所以它是 type 的一个实例。这意味着 objecttype 都是彼此的实例。这不是 "inheritance" 无论您链接的其他答案是什么。该关系与 int1 之间的关系相同:由 1 生成的对象是 int 的实例。这里的怪癖是 objecttype 都是彼此的实例。

从 Python 的角度来看,这两者意味着不同的东西。 object 类型具有本体论作用:一切都是对象(不存在其他任何东西)。所以说 type 是一个对象就意味着它 存在 就 Python 的模型而言。另一方面 object 是所有对象的基类型,所以它是一个类型。作为一种类型,它必须是 type 的实例,就像任何其他对象一样,它是 object.

的实例

就解释器的实现而言:typeobject 的一个实例这一事实很方便,因为它维护了 "everything is an object",这对于例如关闭时释放对象。 objecttype 的一个实例这一事实很有用,因为它straight-forward 确保它的行为与其他类型对象一样。

objecttype之间没有cross-inheritance。其实cross-inheritance是不可能的。

# A type is an object
isinstance(int, object) # True

# But an object is not necessarily a type
isinstance(object(), type) # False

Python 中的真实情况是...

一切都是一个对象

绝对是一切,object是唯一的基本类型。

isinstance(1, object) # True
isinstance('Hello World', object) # True
isinstance(int, object) # True
isinstance(object, object) # True
isinstance(type, object) # True

一切都有类型

任何事物都有一个类型,要么是built-in,要么是user-defined,这个类型可以通过type获得。

type(1) # int
type('Hello World') # str
type(object) # type

不是所有的东西都是类型

那个很明显

isinstance(1, type) # False
isinstance(isinstance, type) # False
isinstance(int, type) # True

type是自己的类型

这是 type 特有的行为,对于任何其他 class 都不可重现。

type(type) # type

换句话说,type 是 Python 中唯一的对象 X 使得 type(X) is X

type(type) is type # True

# While...
type(object) is object # False

这是因为 type 是唯一的 built-in 元 class。 metaclass 只是一个 class,但它的实例本身也是 classes。所以在你的例子中......

# This defines a class
class Foo(object):
    pass

# Its instances are not types
isinstance(Foo(), type) # False

# While this defines a metaclass
class Bar(type):
    pass

# Its instances are types
MyClass = Bar('MyClass', (), {})

isinstance(MyClass, type) # True

# And it is a class
x = MyClass()

isinstance(x, MyClass) # True