问题描述
我一直在阅读有关元类的内容,当涉及类型
和对象
类时,我迷路了。
I've been reading about metaclasses and I got lost when it came to type
and object
classes.
我知道它们位于层次结构的顶层,它们是用C代码实现的。
我也理解类型
继承自对象
以及对象
是类型的实例
。
I understand that they are at the top of the hierarchy and they are implemented in C code.I also understand that type
inherits from object
and that object
is an instance of type
.
在其中一个我在SO上找到了,有人说 - 通过对对象类型
关系的看法 - :
In one of the answers I've found on SO, someone said - in reagards to object-type
relationship - that:
我的问题是为什么以这种方式实现,这种实现的目的是什么?它解决了什么问题/这个设计有什么好处?不能只是类型
或只是对象
类位于每个类继承自的层次结构的顶部?
My question is why is it implemented this way, what is purpose of such implementation? What problems does it solve/what are the benefits of this design? Couldn't it be just type
or just object
class that is at the top of the hierarchy that every class inherits from?
最后,从对象
进行子类化与从类型,我何时想要使用另一个?
Finally, is there any difference between subclassing from object
vs subclassing from type
, and when would I want to use one over the other?
class Foo(object):
pass
vs
class Foo(type):
pass
推荐答案
对象
和类型
之间没有交叉继承。事实上,交叉继承是不可能的。
There is no cross-inheritance between object
and type
. In fact, cross-inheritance is impossible.
# A type is an object
isinstance(int, object) # True
# But an object is not necessarily a type
isinstance(object(), type) # False
Python中的真实情况是...
What is true in Python is that...
绝对一切,对象
是唯一的基本类型。
Absolutly everything, object
is the only base type.
isinstance(1, object) # True
isinstance('Hello World', object) # True
isinstance(int, object) # True
isinstance(object, object) # True
所有 类型
所有内容都有内置或用户定义的类型,并且可以使用类型
获取此类型。
type(1) # int
type('Hello World') # str
type(object) # type
并非一切都是类型
那一个是相当的bvious
Not everything is a type
That one is fairly obvious
isinstance(1, type) # False
isinstance(isinstance, type) # False
isinstance(int, type) # True
type
是它自己的类型
这是特定于类型
的行为,对于任何其他类都不可重现。
type
is its own type
This is the behaviour which is specific to type
and that is not reproducible for any other class.
type(type) # type
换句话说, type
是Python中唯一的对象
In other word, type
is the only object in Python such that
type(type) is type # True
# While...
type(object) is object # False
这是因为 type
是唯一的内置元类。元类只是一个类,但它的实例也是类本身。所以在你的例子中...
This is because type
is the only built-in metaclass. A metaclass is simply a class, but its instances are also classes themselves. So in your example...
# 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
这篇关于在Python3中子类化类型与对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!