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
469 views
in Technique[技术] by (71.8m points)

python - Writing to module-wide variable

Lets say I have these 3 (tiny) python files -

a.py

myvar = 'a'

b.py

import a
import c

myvar = 'b'
c.pr()

c.py

from a import myvar

def pr():
    print myvar

Now if I execute b.py I get output

a

But I really want output to be as

b

So please tell me how can I restructure/modify the programs so that the module-wide myvar can be assigned a different value.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In b.py, you are setting b.py's myvar. You want to access a's value of myvar. So b.py might look like:

import a
import c

a.myvar = 'b' # belongs to a
myvar = 'something different' # belongs to b
c.pr()

And you need to update c.py so that it uses a.py's myvar, not it's own local copy. So c.py:

import a

def pr():
    print a.myvar

Why?

In your original c.py, when you call from a import myvar, this is equivalent to:

import a
myvar = a.myvar

This makes a local version of myvar in c.py upon import. If this is confusing, I found this article about how python variables work very informative.


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

...