在Python之间共享类之间的全局变量 [英] Sharing global variables between classes in Python

查看:1662
本文介绍了在Python之间共享类之间的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p

在面向对象编程方面,我相对来说不太考虑python。

是否可以传递全局变量之间有多个函数的类之间?我已经在这里和其他来源广泛阅读了他们,但我还是有点困惑。



我的最终目标是在全局定义一个变量,值在一个类的函数中,然后在另一个类的函数中使用它。那可能吗?我正在为ArcMap构建一个pythonaddin,它需要为每个按钮一个类。我想要一个按钮给一个变量赋值,然后在脚本中的另一个类中使用该变量。



(在我得到flak之前,我知道



例如,作为一个高度简化的例子:

  x = [] 

A类():

def func_1 b $ b #populate x变量
全局x
x = 1


类B():

def func_2 :
global x
#do stuff with x

如果不是pythonic)?

解决方案

更多的Pythonic解决方案将是有按钮对象event)设置一个属性或调用任何对象所需的方法。


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

解决方案

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.

这篇关于在Python之间共享类之间的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆