我一直在阅读有关元类的内容,但当涉及到 type
和 object
类时,我迷路了。
我知道它们位于层次结构的顶部,并且是用 C 代码实现的。
我还了解到 type
继承自 object
而 object
是 type
的一个实例。
在 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.
我的问题是为什么要这样实现,这样实现的目的是什么?它解决了什么问题/这种设计有什么好处?难道不能只是 type
或 object
类位于每个类继承的层次结构的顶部吗?
最后,object
的子类化与 type
的子类化之间有什么区别吗?我什么时候想使用一个而不是另一个?
class Foo(object):
pass
对比
class Foo(type):
pass
object
和type
之间没有交叉继承。事实上,交叉继承是不可能的。
# 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