您能否解释以下代码段为何无效?
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)
或者
class A:
@staticmethod
def f():
print('A.f')
dict = {'f': lambda: A.f()}
def callMe(g):
g()
callMe(A.dict['f'])
给出预期的结果
A.f
据我所见,Python 2和3中的行为是相同的。
f
里面的对象A
是一个描述符,而不是静态方法本身,当用A的实例调用时,它返回静态方法。阅读链接,并查找“描述符协议”以了解有关其工作原理的更多信息。方法本身存储为__func__
描述符的属性。
您可以自己查看:
>>> 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.__dict__
访问f
描述符对象,而无需创建自己的字典来存储它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句