In python 2.7, I want to create a static variable which stores the result of running a static method of the enclosing class.
I tried the following:
class A: @staticmethod def foo(): return 1 v = A.foo() # a static variable print A.v which returns the error:
NameError: name 'A' is not defined However, referring to another class' static variable works:
class B: @staticmethod def foo(): return 1 class A: @staticmethod def foo(): return 1 v = B.foo() print A.v >>> 1 Any explanations?
EDIT:
The use-case for this scenario is caching the result of foo, and enclose it under A's name space. Following the answers I understand that A is not yet defined at the execution time, which leads to an error. I came up with the following to delay the computation:
class A: @staticmethod def foo(): print 'running foo' return 1 @staticmethod def get_v(): try: return A.v except AttributeError: A.v = A.foo() return A.v print A.get_v() print A.get_v() >>> running foo >>> 1 >>> 1 This seems to do the job, but is somewhat cumbersome.
Adoesn't even exist, hence the error.foo()outside of the class and make it a function, but I suspect you want to do something more complicated.