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

se7*_*7en 15 python methods class-attributes

我注意到,如果我在创建该类的实例时定义一个等于函数的类属性,该属性将成为绑定方法.有人能解释一下这种行为的原因吗?

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)
Run Code Online (Sandbox Code Playgroud)

Mr.*_*. E 12

您为该属性分配了一个函数f.因为函数现在在一个类中它变成了一个方法,特别是一个绑定方法(因为它与对象绑定,这里进一步说明).

类中的方法至少接收一个参数(self),除非特别告诉它 - 参见类方法和静态方法 - 因此错误说不func带参数(如它定义的那样def func():)但收到1(self)

要做你想做的事,你应该告诉python你正在使用静态方法

def func():
    pass

class A(object):
    f = staticmethod(func)
Run Code Online (Sandbox Code Playgroud)