Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

scope - Python: Sharing global variables between modules and classes therein

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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...