python – 内置类型和用户定义之间的不一致

在阅读有关 unification of types内容时,我偶然发现内置类型有method_descriptors和builtin_function_or_methods而不是方法函数,为什么呢?
>>> list.append
<method 'append' of 'list' objects>
>>> type(list.append)
<class 'method_descriptor'>
>>> [].append
<built-in method append of list object at 0x7f0c4214aef0>
>>> type([].append)
<class 'builtin_function_or_method'>
>>> class A(list):
...   def append(self): pass
... 
>>> A.append
<function A.append at 0x7f0c42168dd0>
>>> type(A.append)
<class 'function'>
>>> A().append
<bound method A.append of []>
>>> type(A().append)
<class 'method'>

A类到子类列表没有充分的理由,我只是想表明类型不同.

解决方法

区别在于内置输入是C编译的代码描述符,而用户定义的函数代表它的代码 descriptors.有关详细信息,请参阅 source.

此外,虽然内置函数及其方法是静态分配的数据结构,但用户定义的数据结构的内存是以动态方式分配的.甚至大小也不同:描述符的大小在内置函数之间以及类似的用户定义中是相等的,参考C源(上面的链接):

>>> sys.getsizeof(list.append)
72   # built-in
>>> sys.getsizeof(dir)
72   # built-in
>>> sys.getsizeof(A.__init__)
80   # class/instance method
>>> sys.getsizeof(lambda x: x)
120  # static function

所以这些东西看起来不同,居住在不同的地方,表现不同.没有必要给他们相同的名字.

我想为classmethod添加错过的编译模拟,classmethod_descriptor,

>>> type(float.__dict__['fromhex'])
<type 'classmethod_descriptor'>

以及其他一些有趣的类型:

>>> type(A.__init__)
<type 'wrapper_descriptor'>
>>> type(A.__dict__['__dict__'])
<type 'getset_descriptor'>

看到:

> What is a wrapper_descriptor,and why is Foo.__init__ one in this case
> What is the __dict__.__dict__ attribute of a Python class?

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...