Sharing global variables between classes in Python

2020-07-09 08:29发布

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)?

3条回答
我命由我不由天
2楼-- · 2020-07-09 08:43

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.

查看更多
男人必须洒脱
3楼-- · 2020-07-09 08:44

Yes, it is possible. Your code is almost right, just missing a couple of parenthesis in the function definitions. Other than that, it works.

Now, is that acceptable? In 99% of cases, no, it's not. There're many ways of passing variables and sharing data between classes, and using global variables is one of the worse ones, if not the worst.

查看更多
做个烂人
4楼-- · 2020-07-09 09:10

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.

查看更多
登录 后发表回答