Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中传递静态方法_Python_Static Methods - Fatal编程技术网

在python中传递静态方法

在python中传递静态方法,python,static-methods,Python,Static Methods,您能解释一下为什么下面的代码段不起作用吗 class A: @staticmethod def f(): print('A.f') dict = {'f': f} def callMe(g): g() callMe(A.dict['f']) 它产生 TypeError: 'staticmethod' object is not callable 有趣的是,将其更改为 class A: @staticmethod def f

您能解释一下为什么下面的代码段不起作用吗

class A:
    @staticmethod
    def f():
        print('A.f')

    dict = {'f': f}

def callMe(g):
    g()

callMe(A.dict['f'])
它产生

TypeError: 'staticmethod' object is not callable
有趣的是,将其更改为

class A:
    @staticmethod
    def f():
        print('A.f')

    dict = {'f': f}

def callMe(g):
    g()

callMe(A.f)

给出了预期的结果

A.f

就我所见,Python 2和Python 3中的行为是相同的。

A中的
f
对象是A,而不是静态方法本身——当使用A的实例调用时,它返回staticmethod;阅读链接,并查找“描述符协议”以了解更多有关其工作原理的信息。方法本身存储为描述符的
\uuuu func\uuu
属性

您可以亲自看到这一点:

>>> A.f
<function A.f at 0x7fa8acc7ca60>
>>> A.__dict__['f']
<staticmethod object at 0x7fa8acc990b8>
>>> A.__dict__['f'].__func__ # The stored method
<function A.f at 0x7fa8acc7ca60>
>>> A.__dict__['f'].__get__(A) # This is (kinda) what happens when you run A.f
<function A.f at 0x7fa8acc7ca60>
>>A.f
>>>A..uuu dict_uuu['f']
>>>A.uu dict_uu['f']。uu func_35;存储方法
>>>A.uuu dict_uuu['f']。uuu get_uuu(A)#这是(有点)当你运行A.f.时发生的事情

还请注意,您可以使用
A.\uu dict\uu
访问
f
描述符对象,您不需要制作自己的字典来存储它

staticmethod对象是一个,您需要将其作为(类的)属性进行访问,描述符机制才能生效。staticmethod对象本身是不可调用的,但其
\uuuu get\uuuu
的结果是可调用的。另见

>>> A.f
<function A.f at 0x7fa8acc7ca60>
>>> A.__dict__['f']
<staticmethod object at 0x7fa8acc990b8>
>>> A.__dict__['f'].__func__ # The stored method
<function A.f at 0x7fa8acc7ca60>
>>> A.__dict__['f'].__get__(A) # This is (kinda) what happens when you run A.f
<function A.f at 0x7fa8acc7ca60>