TimW
TimW

Reputation: 43

Python 2.7: initializing static variables by calling a staticmethod

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

Answers (1)

Mike M&#252;ller
Mike M&#252;ller

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 objectin order to get a new style class.

Upvotes: 1

Related Questions