众所周知,Python 2.x 中有两种类型的类,如旧样式类和新样式类
class OldStyle:
pass
Oldstyle 类的type
实例总是instance
class NewStyle(object):
pass
新样式类有,等优点method descriptors
, NewStyle 类的实例就是类名本身super
getattribute
type
当您检查 NewStyle 类的类型是类型并且类型object
也是类型时
In [5]: type(NewStyle)
Out[5]: type
In [6]: type(object)
Out[6]: type
In [7]: type(type)
Out[7]: type
那么继承新样式类的概念是什么object
,正如我们在上面看到的那样,type(type)
也是type
,type(object)
也是type
为什么我们不能直接继承新的样式类type
?
我们可以假设以下几点来区分object
和type
吗?
- 如果我们从下面继承/创建一个类
type
,我们肯定会最终创建一个元类吗?(一切都是python中的对象,包括类,都是其他类的对象type
)
class NewStyle(type):
pass
当 Python 解释器看到上面的代码时,它会创建一个类型为class
(类对象)的对象/实例,名称为 NewStyle(它不是普通实例,而是类对象)
- 如果我们从 继承/创建一个类
object
,它将创建该类的普通实例/对象
class NewStyle(object):
pass
isinstance(NewStyle, type)
obj = NewStyle()
print isinstance(obj, NewStyle) # True
print isinstance(NewStyle, type) #True
print isinstance(NewStyle, object) #True
print isinstance(object, type) # True
print isinstance(type, object) # True
那么最后我们使用type
创建类,但我们使用object
创建实例?