python模块间共享全局变量_Python:在其中的模块和类之间共享全局变量

I know that it's possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example,

global_mod.py

x = None

mid_access_mod.py

from global_mod import *

class delta:

def __init__(self):

print x

bot_modif_mod.py

import mid_access_mod

import global_mod

class mew:

def __init__(self):

global_mod.x = 5

def main():

m = mew()

d = mid_access_mod.delta()

This prints None, even though all the modules are sharing the global variable x. Why is this the case? It seems like x is evaluated at mid_access_mod.py before it is assigned in bot_modif_mod.py by mew().

解决方案

This happens because you are using immutable values (ints and None), and importing variables is like passing things by value, not passing things by reference.

If you made global_mod.x a list, and manipulated its first element, it would work as you expect.

When you do from global_mod import x, you are creating a name x in your module with the same value as x has in global_mod. For things like functions and classes, this works as you would expect, because people (generally) don't re-assign to those names later.

As Alex points out, if you use import global_mod, and then global_mod.x, you will avoid the problem. The name you define in your module will be global_mod, which always refers to the module you want, and then using attribute access to get at x will get you the latest value of x.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值