How to declare a global variable from a class?

I am trying to declare a global variable from within such a class:

class myclass: global myvar = 'something' 

I need it to be accessible outside the class, but I do not want to declare it outside the class file. My question is: is this possible? If so, what is the syntax?

+8
python class
source share
5 answers

In your question, you indicate "outside the main file." If you did not mean "outside the class", then this will work to determine the module level variable:

 myvar = 'something' class myclass: pass 

Then you can do it by counting the class and variable definitions in the module named mymodule :

 import mymodule myinstance = myclass() print mymodule.myvar 

Also, in response to your comment in @phihag's answer, you can access myvar without qualification:

 from mymodule import myvar print myvar 

If you just want to open its shorthand from another file, still defining it in the class:

 class myclass: myvar = 'something' 

then in the file where you need to access it, assign a link in the local namespace:

 myvar = myclass.myvar print myvar 
+12
source share

You can simply assign a property to a class:

 class myclass(object): myvar = 'something' # alternatively myclass.myvar = 'else' # somewhere else ... print(myclass.myvar) 
+3
source share

You must really rethink whether this is really necessary, this seems like a strange way to structure your program, and you should use the phihag method more correctly.

If you decide you want to do this, here is how you can:

 >>> class myclass(object): ... global myvar ... myvar = 'something' ... >>> myvar 'something' 
+3
source share

To answer your question

 global s s = 5 

Do it. You will run into problems depending on where in your class you do it. Stay away from functions to get the right behavior.

+3
source share

You can do as

 # I don't like this hackish way :-S # Want to declare hackish_global_var = 'something' as global global_var = globals() global_var['hackish_global_var'] = 'something' 
+3
source share

All Articles