当我在类的内部使用静态方法,并使用内置的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
所以我的问题是:
有没有更简洁、更符合 Python 风格的方法来实现这个功能?
staticmethod
。它们通常作为模块级别的函数更有用,这种情况下你的问题就不是问题了。另一方面,classmethod
... - Benjamin Hodgson