python - Python3 中的子类化类型与对象

标签 python inheritance metaclass

<分区>

我一直在阅读有关元类的内容,但当涉及到 typeobject 类时,我迷路了。

我知道它们位于层次结构的顶部,并且是用 C 代码实现的。 我还了解到 type 继承自 objectobjecttype 的一个实例。

answers 之一中我在 SO 上发现,有人说 - 关于 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.

我的问题是为什么要这样实现,这样实现的目的是什么?它解决了什么问题/这种设计有什么好处?难道不能只是 typeobject 类位于每个类继承的层次结构的顶部吗?

最后,object 的子类化与 type 的子类化之间有什么区别吗?我什么时候想使用一个而不是另一个?

class Foo(object):
    pass

对比

class Foo(type):
    pass

最佳答案

objecttype 之间没有交叉继承。事实上,交叉继承是不可能的。

# 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

一切都有类型

任何事物都有一个类型,要么是内置的,要么是用户定义的,这个类型可以通过 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 的行为,对于任何其他类都是不可重现的。

type(type) # type

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

type(type) is type # True

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

这是因为 type 是唯一的内置元类。元类只是一个类,但它的实例本身也是类。所以在你的例子中......

# 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

关于python - Python3 中的子类化类型与对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50270155/

相关文章:

c# - 从基类强制转换为继承类时,InvalidCastException?

excel - VBA通过构造继承,构造函数不起作用?

C++ 和引用资料

python - 包含第一个元素的反向数组切片

python - 从用户输入创建动态命名的变量

python - 使用参数从 Python 调用 C/C++ 代码

python - 如何覆盖 GAE 中的 HTTP 请求动词

python - 提供不同线性代数后端的架构

python - 在 python 2 中为类设置 __doc__

python - PyMongo - 查询嵌入文档列表