简体   繁体   English

在Python中的类之间共享全局变量

[英]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. 在面向对象编程方面,我对python的思考相对较新,而且对我而言相对较慢。

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. 我正在为ArcMap构建一个pythonaddin,它需要每个按钮都有一个类。 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)? 这是否可以接受(即使不是pythonic)?

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. 它可以正确打印列表x 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. PS:注意函数中的参数。

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. 在99%的情况下,不,不是。 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 . 在类之间传递变量和共享数据有很多种方法,使用全局变量是最差的方法之一,如果不是最差的话

一个更Pythonic的解决方案是让按钮对象(在处理“press”事件的方法中)设置属性或调用任何对象需要信息的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM