Python版本 <= 3.9:在类体内调用类的staticmethod?

6 浏览
0 Comments

Python版本 <= 3.9:在类体内调用类的staticmethod?

当我试图在类的主体中使用静态方法,并且使用内置的staticmethod函数作为装饰器来定义静态方法时,如下所示:

class Klass(object):
    @staticmethod  # 作为装饰器使用
    def _stat_func():
        return 42
    _ANS = _stat_func()  # 调用静态方法
    def method(self):
        ret = Klass._stat_func() + Klass._ANS
        return ret

我得到以下错误:

Traceback (most recent call last):

File "call_staticmethod.py", line 1, in

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()  # 使用非静态方法版本
    _stat_func = staticmethod(_stat_func)  # 将函数转换为静态方法
    def method(self):
        ret = Klass._stat_func() + Klass._ANS
        return ret

所以我的问题是:

    有没有更清晰或更符合Python风格的方法来实现这个?

0