首页 > 解决方案 > python中的对象和类型有什么区别

问题描述

众所周知,Python 2.x 中有两种类型的类,如旧样式类和新样式类

class OldStyle:
    pass

Oldstyle 类的type实例总是instance

class NewStyle(object):
    pass

新样式类有,等优点method descriptors, NewStyle 类的实例就是类名本身supergetattributetype

当您检查 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)也是typetype(object)也是type

为什么我们不能直接继承新的样式类type

我们可以假设以下几点来区分objecttype吗?

  1. 如果我们从下面继承/创建一个类type,我们肯定会最终创建一个元类吗?(一切都是python中的对象,包括类,都是其他类的对象type

class NewStyle(type): pass

当 Python 解释器看到上面的代码时,它会创建一个类型为class(类对象)的对象/实例,名称为 NewStyle(它不是普通实例,而是类对象)

  1. 如果我们从 继承/创建一个类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创建实例?

标签: pythonobjectnew-style-class

解决方案


推荐阅读