Sharing global variables between classes in Python

旧街凉风 提交于 2020-01-02 02:40:08

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20181830/sharing-global-variables-between-classes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!