您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:21 python 字数 3145 阅读 473 来源 www.jb51.cc/python

在阅读有关 unification of types的内容时,我偶然发现内置类型有method_descriptors和builtin_function_or_methods而不是方法和函数,为什么呢? >>> list.append <method 'append' of 'list' objects> >>> type(list.append) <class 'method_descripto

概述

>>> 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源(上面的链接):

>>> 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@H_419_27@> What is the __dict__.__dict__ attribute of a Python class?

总结

以上是编程之家为你收集整理的python – 内置类型和用户定义之间的不一致全部内容,希望文章能够帮你解决python – 内置类型和用户定义之间的不一致所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶