gpt4 book ai didi

python - Python 3 中的 'function' 、 'method' 和 'bound method' 之间有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 23:58:09 24 4
gpt4 key购买 nike

我观察到至少 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>

我想知道“函数”、“方法”和“绑定(bind)方法”之间有什么区别? “方法”是 Python 2 中等同于“未绑定(bind)方法”的类型吗?

最佳答案

Is 'method' a type equivalent to 'unbound method' in Python 2?

有点像。但不是真的。这是一个method_descriptor C 代码中定义的对象。它是一个未绑定(bind)的方法,但不是您在 Python 2 中找到的那种方法。

对于用 C 编写的 Python 类型,所有“方法”实际上都是 C 函数。 <method 'name' of 'type' objects>你找到的对象是一个特殊的对象,你可以使用它来调用给定实例和更多参数的函数,就像 function object 为自定义 Python 类做的。该对象在 PyMethodDescr_Type structure 中用 C 语言定义.它实现了 descriptor protocol ,就像函数一样。

Python 定义了其他几个这样的描述符类型;如果你使用 __slots__ , 每个属性都是一个 member_descriptor 类型的描述符(参见 PyMemberDescr_Type structure ),而 classmethod , propertystaticmethod可能是更广为人知的描述符对象。

在 Python 2 中,绑定(bind)和未绑定(bind)方法实际上只是一种类型,instancemethod (由 PyMethod_Type structure 定义);如果 __self__ 它将报告为绑定(bind)( im_self ) 属性已设置。在 Python 3 中,使用函数作为描述符不会在没有 __self__ 的情况下生成方法对象。放;而不是调用 function.__get__()没有实例只是再次返回函数。

Python 2 返回未绑定(bind)方法的唯一原因是强制执行类型检查;第一个参数必须是该类(或其子类)的实例。这对于支持鸭子类型的 Python 代码没有多大意义,因此在 Python 3 中删除了限制。但是,对于 C 代码,您不能使用 duck-typing,您仍然必须限制类型,这就是 C-types 仍然返回 method_descriptor 的原因。实现此限制的对象。

关于python - Python 3 中的 'function' 、 'method' 和 'bound method' 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35174759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com