问题
SO pyton gurus! I've just found an astonishing phenomenon that I don't understand. The problem can be best shown as code:
#== kid.py ==#
import dad
def spam ():
dad.spam()
#== dad.py ==#
import kid
x = 1
print "body", x
x = 2
def spam ():
print "spam", x
if __name__ == '__main__':
x = 3
spam()
kid.spam()
print "main", x
I'm using Python 2.7.3. Can you guess the output of python dad.py
? The answer is (I wish SO had a spoiler shading tag) body 1 body 1 spam 3 spam 2 main 3
. So could you explain
- Why is
body 1
printed twice? - How can
dad.x != kid.dad.x
be? - If I really need to make the two modules import each other, how can I modify it to get
kid.dad.x
properly updated?
回答1:
- Because loading dad.py as the
__main__
module is independent of importing dad.py as thedad
module. - See my answer to 1.
- Import
__main__
instead if you must. But in general, don't try this. Find another way to accomplish your tasks (e.g. classes).
Printing __name__
at the top of dad.py will illustrate this.
来源:https://stackoverflow.com/questions/12242417/changing-module-variables-after-import