How do I statically (i.e. in the class body) call a staticmethod
which calls another staticmethod
in Python 3.6?
I would like to use a staticmethod
to initialize a static member of my class. The problem is that I'm trying to refer to my class before it has been created (unlike in this question).
Below is an example of my problem. I was actually trying to initialize a static dictionary using dictionary comprehension which makes use of a static function, so I've included an example of that too. I managed to solve that using a basic loop, but there are also other ways to use comprehensions statically.
class Test:
@staticmethod
def something(q):
return q + 10
@staticmethod
def foo(x):
return "Hello {0}".format(Test.something(x))
# **** foo is called, but throws error at call to Test.something() ****
#print(foo.__func__(4))
# something() is also used by itself.
print(something.__func__(2))
# My problem involved initializing a dictionary. Solved using loop.
a = [1,2,3,4]
#d = {k: "yup" for k in a} # Dictionary comprehension works
#d = {k: Test.something.__func__(k) for k in a} # Error, Test/something not defined
d = {}
for k in a:
d[k] = something.__func__(k)
print(Test.foo(5)) # Works, class defined (but not what I need).
EDIT: This does not appear to be a duplicate of Calling class staticmethod within the class body?. This question is explicitly asking how to call one staticmethod from another in the class body, whereas the other question only asks how to call a staticmethod within the class body. (In any case, the best solution seems to be to do away with the staticmethod and use a module-level function instead)