How to declare a global variable from within a class?

Question:

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?

Asked By: Adam

||

Answers:

You can simply assign a property to the class:

class myclass(object):
   myvar = 'something'

# alternatively
myclass.myvar = 'else'

# somewhere else ...
print(myclass.myvar)
Answered By: phihag

In your question, you specify "outside the main file". If you didn’t mean "outside the class", then this will work to define a module-level variable:

myvar = 'something'

class myclass:
    pass

Then you can do, assuming the class and variable definitions are in a module called mymodule:

import mymodule

myinstance = myclass()
print(mymodule.myvar)

Also, in response to your comment on @phihag’s answer, you can access myvar unqualified like so:

from mymodule import myvar

print(myvar)

If you want to just access it shorthand from another file while still defining it in the class:

class myclass:
    myvar = 'something'

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

myvar = myclass.myvar

print(myvar)

Answered By: zigg

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'
Answered By: Andrew Clark

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.

Answered By: 8bitwide

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'
Answered By: 0xc0de

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)

Answered By: Shivaank Tripathi

You can increment a global class variable as follows –

class Employee():
   num_of_employees = 0

   def __init__(self):
       self.name = ''
       Employee.num_of_employees += 1

Here, num_of_employees variable will be updated everytime a new class object is created, and it’s value will be shared across all the objects

Answered By: Malgo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.