1

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
1
  • I suppose one workaround is to pass varA into func. Commented Feb 14, 2018 at 19:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.