Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing global variables between classes in Python

I'm relatively new to thinking of python in terms of object-oriented programming, and it's coming relatively slowly to me.

Is it possible to pass global variables between classes with multiple functions in them? I've read extensively about them here and in other sources, but I'm still a bit confused.

My ultimate goal is to define a variable globally, assign it a value in a function of one class, and then USE it in another class's function. Is that possible? I'm building a pythonaddin for ArcMap, which requires a class for each button. I want to have a button to assign a value to a variable, and then use that variable in another class in the script.

(Before I get the flak, I know it's relatively bad form to use global variables in the first place, I'm trying to learn)

For instance, as a highly simplified example:

x = []

class A():

    def func_1(self): 
        #populate the x variable
        global x 
        x = 1


class B():

    def func_2(self):
        global x
        #do stuff with x

Is this acceptable (even if not pythonic)?

like image 413
user22861 Avatar asked Nov 24 '13 22:11

user22861


People also ask

How can you share global variables across module?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

Are global variables shared between modules?

How can you share global variables across modules? We can create a config file & store the entire global variable to be shared across modules or script in it. By simply importing config, the entire global variable defined it will be available for use in other modules.

Can global variables be accessed outside the class?

In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.


2 Answers

Yes, it can work. Here is the modified code:

x = []

class A:
    def func_1(self):
        #populate the x variable
        global x 
        x.append(1)
class B:
    def func_2(self):
        global x
        print x

a = A()
a.func_1()
b = B()
b.func_2()

It can print the list x correctly. When it's possible, you should try to avoid global variables. You can use many other ways to pass variables between classes more safely and efficiently.

PS: Notice the parameters in the functions.

like image 67
Old Panda Avatar answered Oct 06 '22 01:10

Old Panda


A more Pythonic solution would be to have the button objects (in their method that handles the "press" event) set an attribute or call a method of whatever object needs the information.

like image 38
Roland Smith Avatar answered Oct 06 '22 00:10

Roland Smith