Называете класс статическим методом внутри тела класса?
Когда я пытаюсь использовать статический метод изнутри тела класса, и определить статический метод с помощью встроенного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):<br>
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
I understand why this is happening (descriptor binding)и может обойти это путем ручного преобразования_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
Итак, мой вопрос:
Are there better, as in cleaner or more "Pythonic", ways to accomplish this?