加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:32:44 所属栏目:Python 来源:网络整理
导读:在阅读有关 unification of types的内容时,我偶然发现内置类型有method_descriptors和builtin_function_or_methods而不是方法和函数,为什么呢? list.appendmethod 'append' of 'list' objects type(list.append)class 'method_descriptor' [].appendbuilt-i
在阅读有关 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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读