'How to declare a global variable from within a class?

I'm trying to declare a global variable from within a class like so:

class myclass:
    global myvar = 'something'

I need it to be accessed outside the class, but I don't want to have to declare it outside the class file. My question is, is this possible? If so, what is the syntax?



Solution 1:[1]

You should really rethink whether or not this is really necessary, it seems like a strange way to structure your program and you should phihag's method which is more correct.

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

>>> class myclass(object):
...     global myvar
...     myvar = 'something'
...
>>> myvar
'something'

Solution 2:[2]

You can do like

# 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'

Solution 3:[3]

You can simply assign a property to the class:

class myclass(object):
   myvar = 'something'

# alternatively
myclass.myvar = 'else'

# somewhere else ...
print(myclass.myvar)

Solution 4:[4]

To answer your question

global s
s = 5

Will do it. You will run into problems depending on where in your class you do this though. Stay away from functions to get the behavior you want.

Solution 5:[5]

Global variable within a class can also be defined as:

    class Classname:
       name = 'Myname'

    # To access the variable name in a function inside this class:
    def myfunc(self):
        print(Classname.name)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Clark
Solution 2 0xc0de
Solution 3 phihag
Solution 4 8bitwide
Solution 5 Shivaank Tripathi