gpt4 book ai didi

Python - 作为类属性的函数成为绑定(bind)方法

转载 作者:太空狗 更新时间:2023-10-29 17:18:55 25 4
gpt4 key购买 nike

我注意到,如果我在创建该类的实例时将类属性定义为函数,则该属性将成为绑定(bind)方法。有人可以向我解释这种行为的原因吗?

In [9]: def func():
...: pass
...:

In [10]: class A(object):
....: f = func
....:

In [11]: a = A()

In [12]: a.f
Out[12]: <bound method A.func of <__main__.A object at 0x104add190>>

In [13]: a.f()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-19134f1ad9a8> in <module>()
----> 1 a.f()
global a.f = <bound method A.func of <__main__.A object at 0x104add190>>

TypeError: func() takes no arguments (1 given)

最佳答案

您为属性A.f(类A 的属性f)分配了一个函数。属性 A.f 被定义为类的一部分。它是一个函数,因此默认情况下它是该类的实例方法

创建类 A 的实例(名为 a)会导致该实例具有属性 f,您可以通过名称访问它a.f。这是一个绑定(bind)方法(因为它绑定(bind)到对象 a; further explanation here )。

每个实例方法在调用时都会自动接收实例作为其第一个参数(通常命名为 self)。其他类型的方法也是可能的:- 参见 class methods and static methods .

由于这个原因,错误表明 func 没有参数(因为它被定义为 def func():)但是收到了 1 (self).

要做你想做的事,你应该告诉 python 你正在使用 static method

def func():
pass

class A(object):
f = staticmethod(func)

关于Python - 作为类属性的函数成为绑定(bind)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35321744/

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