python - python中的对象和类型有什么区别
问题描述
众所周知,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
创建实例?
解决方案
推荐阅读
- python - 如何在 Django 中为每个所有者(外键)增加“数字”字段
- verification - 为什么我在 promela 中会出现这样的错误?
- php - PHP - 空合并运算符
- schedule - 如何将 Autosys 扩展日历配置为在每个季度的前 14 天运行
- python - 使用 python 的 Cloud Firestore
- python - 在 Python 中创建 3D 数组
- python - 如何在 django 视图中获取隐藏输入的值
- java - 在java的整个程序中使用一个sql连接对象
- vue.js - Laravel 根据路线更改布尔值
- inno-setup - 避免重复安装两次的相同安装程序