Python 一切皆对象的本质
尝试用python的概念,解释python自身的底层原理
class PyObject:
def __init__(
self,
ob_refcnt=1,
ob_type=None
):
self.ob_refcnt: int = ob_refcnt
self.ob_type: PyTypeObject = ob_type
这是一个C语言的结构体,现在我们把它用python的形式展现出来。一切python对象,底层实习都会包含PyObject。因为C语言可以强转和内存对齐。所以实际上他是类似于python的继承。如果你熟悉java的向上转型,那么理解起来会很容易。
所以一切Python对象都可以用PyObject来表示,它们之间的不同是,在PyObject之外多了一些额外的不同数据。
PyObject记录了两个信息:
- ob_refcnt 引用计数,默认为1
- ob_type 对象的类型,其指向一个类对象
好,现在让我们回想。python的类也是一个对象
class PyTypeObject(PyObject):
def __init__(
self,
new=None,
init=None,
call=None,
ob_refcnt=1,
ob_type=None
):
super().__init__(ob_refcnt, ob_type)
self.new = new
self.init = init
self.call = call
我们建立一个这样的类,他是PyObject的扩展,额外包含了很多东西。我们这里给它加入三个方法,new, init, call。
我们尝试建立一个类
new_cls = PyTypeObject(ob_type=???)
def class_new(cls):
return PyObject(ob_type=cls)
def class_init(self):
pass
def class_call(cls, *args, **kwargs):
instance = cls.new(cls)
cls.init(instance, *args, **kwargs)
return instance
new_cls.new = class_new
new_cls.init = class_init
new_cls.call = class_call
这样这个类具有产生实例的能力了,我们只需要调用他的call()方法,一个PyObject实例便由此产生。且其ob_type,指向这个类。
不过这里的new, init, call不能完全对应__ new __, __ init __, __ call __ 。这里只是底层的表示。像python中类中定义的 __ call __ 实际上是实例的 __ call __,而不是类自身的。
我们会发现一个问题
第一句中定义类对象的时候,我们没有指出ob_type,也就是类的类型。
如果你了解python,那么一定知道元类,实际上元类就是这个类的ob_type。
我们知道元类的可以产生类。
同时元类本身也是一个类,我们可以看成一个特殊的类。
我们可以来create一个type对象,在全局作用域上。
PyType_Type = PyTypeObject()
def type_new(msc: PyTypeObject):
return PyTypeObject(ob_type=msc)
def type_init(new_cls: PyTypeObject, **new_kwargs):
def class_new(cls):
return PyObject(ob_type=cls)
def class_init(self):
pass
def class_call(cls, *args, **kwargs):
instance = cls.new(cls)
cls.init(instance, *args, **kwargs)
return instance
new_cls.new = class_new
new_cls.init = class_init
new_cls.call = class_call
for k, v in new_kwargs:
setattr(new_cls, k, v)
def type_call(msc: PyTypeObject, **kwargs):
cls: PyTypeObject = msc.new(msc)
msc.init(cls, **kwargs)
return cls
PyType_Type.new = type_new
PyType_Type.init = type_init
PyType_Type.call = type_call
PyType_Type.ob_type = PyType_Type
把之前普通类定义的代码放到其中,这样一个会产生类对象的。
因为python没有指针,无法做到
PyType_Type = PyTypeObject(ob_type=PyType_Type)
所以我们在对象建立后,再将其指向自己。
这个PyType_Type,实际上就是python中的type对象。
当然我们知道,还有个全局的对象是object。
我们现在建一个就好了。
PyBaseObject_Type = PyType_Type.call(PyType_Type)
这样一组低配的type和object就建立好了
还有一点,就是继承,我们在此忽略了这点。
如果你了解过元类,一定知道一个特别绕的概念
object的类型是type,type的父类是object
实际上我们在上述两个结构体对象建立只有,将指针互相指向对方便可以实现。
NewClass = PyType_Type.call(PyType_Type)
print(NewClass)
NewObject = NewClass.call(NewClass)
print(NewObject)
