python - 内置类型和用户定义的不一致

标签 python types

在阅读 unification of types 时我偶然发现内置类型具有 method_descriptorbuiltin_function_or_method 而不是 methodfunction为什么?

>>> 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'>

没有充分的理由让 class 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 添加错过的编译模拟, 类方法描述符,

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

和其他一些有趣的类型:

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

参见:

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

关于python - 内置类型和用户定义的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892159/

相关文章:

python - HSB颜色范围,适用于VIBGYOR颜色

Python 多处理 : object passed by value?

python - 对预标记化文本使用 spacy

.net - 在 F# 中强制任何对象为 null

python - NodeJs : Get output of python-shell to send back to client

python - 从python中的多个线程捕获打印输出

C++类型限定符问题

MySQL 主键字段类型

c++ - 何时使用 std::size_t?

haskell - 为什么 (a,b,c,d) 不是 (a,(b,(c,(d,())))) 的糖?