当我尝试在类的主体中使用静态方法时,并使用内置的 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
我理解为什么会发生这种情况(描述符绑定(bind)),并且可以通过在上次使用后手动将 _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”的方法来完成此任务?
最佳答案
python 版本 >= 3.10 的更新:静态方法函数可以在类范围内调用(有关更多信息,请参阅:python issue tracker 或 "what's new" 或 here)
for python version <= 3.9 继续阅读
staticmethod
对象显然有一个 __func__
属性存储原始原始函数(这是有道理的,他们必须这样做)。所以这会起作用:
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
_ANS = stat_func.__func__() # call the staticmethod
def method(self):
ret = Klass.stat_func()
return ret
顺便说一句,虽然我怀疑静态方法对象具有某种存储原始函数的属性,但我不知 Prop 体细节。本着授人以鱼不如授人以渔的精神,这就是我所做的调查和发现(来 self 的 Python session 的 C&P):
>>> class Foo(object):
... @staticmethod
... def foo():
... return 3
... global z
... z = foo
>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>
在交互式 session 中进行类似的挖掘(dir
非常有帮助)通常可以非常快速地解决这类问题。
关于Python 版本 <= 3.9 : Calling class staticmethod within the class body?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46086719/