When I attempt to use a static method from within the body of the class, and define the static method using the built-in staticmethod function as a decorator, like this:
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
I get the following error:
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), and can work around it by manually converting _stat_func() into a staticmethod after its last use, like so:
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
So my question is:
Are there better, as in cleaner or more "Pythonic", ways to accomplish this?
staticmethodat all. They are usually more useful as module-level functions, in which case your problem is not an issue.classmethod, on the other hand... - Benjamin Hodgson♦_to a method name is simply a convention to indicate that something is private (although the language doesn't enforce it) — and may or may not have any bearing w.r.t. inheritance. Regardless, the code in my question is simply for illustrating the problem with calling static methods. - martineau_mean protected and double__mean private. Then as I say, in this case applying protected (by calling convention) on static method mean nothing. - CallMarl