Reputation: 43
I am attempting to initialize some static class variables using static functions defined in the class. Python is throwing an error, indicating that the class name is not defined when I call said static function during initialization. Is there a better way to do this? Thank you.
>>> class Example:
... varA = 5
... @staticmethod
... def func():
... return Example.varA + 1
... varB = func.__func__()
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in Example
File "<stdin>", line 5, in func
NameError: global name 'Example' is not defined
Upvotes: 1
Views: 574
Reputation: 85492
You can only access a class after it is defined. Therefore di after the definition:
class Example(object):
varA = 5
@staticmethod
def func():
return Example.varA + 1
Example.varB = Example.func()
This achieves what you want without any static method:
class Example(object):
varA = 5
varB = varA + 1
BTW, in Python 2 you should always inherit form object
in order to get a new style class.
Upvotes: 1