pla*_*etp 6 python function python-3.x python-internals
我观察到至少有3种与Python 3中的函数相关的类型:
>>> class A():
... def f(): pass
...
>>> A.f
<function A.f at 0x7fcaef304268>
>>> A().f
<bound method A.f of <__main__.A object at 0x7fcaef2fae80
>>> set.union
<method 'union' of 'set' objects>
Run Code Online (Sandbox Code Playgroud)
我想知道'function','method'和'bound method'之间的区别是什么?'method'是否等同于Python 2中的'unbound method'?
'method'是否等同于Python 2中的'unbound method'?
那种-A-排序一个.但不是真的.它是method_descriptorC代码中定义的对象.它是一种未绑定的方法,但不是您在Python 2中找到的那种方法.
对于编写C的Python类型,所有'方法'都是C函数.<method 'name' of 'type' objects>您找到的对象是一个特殊对象,您可以使用该对象在给定实例和其他参数的情况下调用该函数,就像function对象对自定义Python类一样.该对象在PyMethodDescr_Type结构中以C定义.它实现了描述符协议,就像函数一样.
Python定义了其他几种描述符类型; 如果你使用__slots__,每个属性类型的dsescriptor member_descriptor(见PyMemberDescr_Type结构),同时classmethod,property和staticmethod也许更广为人知描述符对象.
在Python 2中,绑定和非绑定方法实际上只是一种类型instancemethod(由PyMethod_Type结构定义); 如果设置了__self__(im_self)属性,它将报告为绑定.在Python 3中,使用函数作为描述符只是不生成没有__self__set的方法对象; 相反function.__get__(),没有实例调用只会再次返回该函数.
Python 2返回未绑定方法的唯一原因是强制执行类型检查 ; 第一个参数必须是类的实例(或其子类).对于支持duck-typing的Python代码来说,这并没有多大意义,因此在Python 3中,限制被删除了.但是,对于C代码,您不能使用duck-typing,您仍然必须限制类型,这就是为什么C类型仍然返回method_descriptor强制执行此限制的对象的原因.
| 归档时间: |
|
| 查看次数: |
738 次 |
| 最近记录: |