Adam
Adam

Reputation: 1090

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?

Upvotes: 12

Views: 80601

Answers (7)

Malgo
Malgo

Reputation: 2168

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

Upvotes: 0

Mattie B
Mattie B

Reputation: 21309

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)

Upvotes: 18

Shivaank Tripathi
Shivaank Tripathi

Reputation: 11

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)

Upvotes: 0

0xc0de
0xc0de

Reputation: 8317

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'

Upvotes: 5

8bitwide
8bitwide

Reputation: 2071

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.

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208655

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'

Upvotes: 7

phihag
phihag

Reputation: 288260

You can simply assign a property to the class:

class myclass(object):
   myvar = 'something'

# alternatively
myclass.myvar = 'else'

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

Upvotes: 2

Related Questions