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

博主在尝试理解Python中的面向对象编程,特别是关于全局变量在不同类之间传递的问题。他们希望在定义一个全局变量后,在一个类的方法中赋值,然后在另一个类的方法中使用这个变量。虽然知道全局变量通常不推荐使用,但为了学习,博主正在寻求实现这一目标的方法。一个更Pythonic的解决方案是通过按钮对象的方法来设置属性或者调用需要该信息的对象的方法。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值