【发布时间】:2018-02-15 14:57:55
【问题描述】:
当我尝试从类的主体中使用静态方法,并使用内置的 staticmethod 函数作为装饰器定义静态方法时,如下所示:
class Klass(object):
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = _stat_func() # call the staticmethod
def method(self):
ret = Klass._stat_func() + Klass._ANS
return ret
我收到以下错误:
Traceback (most recent call last):
File "call_staticmethod.py", line 1, in <module>
class Klass(object):
File "call_staticmethod.py", line 7, in Klass
_ANS = _stat_func()
TypeError: 'staticmethod' object is not callable
我理解为什么会发生这种情况(描述符绑定),并且可以通过在上次使用后手动将 _stat_func() 转换为静态方法来解决它,如下所示:
class Klass(object):
def _stat_func():
return 42
_ANS = _stat_func() # use the non-staticmethod version
_stat_func = staticmethod(_stat_func) # convert function to a static method
def method(self):
ret = Klass._stat_func() + Klass._ANS
return ret
所以我的问题是:
是否有更简洁或更“Pythonic”的方式来完成此任务?
【问题讨论】:
-
如果您询问 Pythonicity,那么标准建议是根本不要使用
staticmethod。它们通常作为模块级函数更有用,在这种情况下,您的问题不是问题。classmethod,另一方面... -
@poorsod:是的,我知道这种选择。但是,在我遇到此问题的实际代码中,将函数设为静态方法而不是将其置于模块级别比在我的问题中使用的简单示例中更有意义。
标签: python decorator static-methods