Changing module variables after import

醉酒当歌 提交于 2020-01-07 08:33:30

问题


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

  1. Why is body 1 printed twice?
  2. How can dad.x != kid.dad.x be?
  3. 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:


  1. Because loading dad.py as the __main__ module is independent of importing dad.py as the dad module.
  2. See my answer to 1.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!