导入后更改模块变量 [英] Changing module variables after import

查看:162
本文介绍了导入后更改模块变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO pyton gurus!我刚刚发现了一个我不明白的惊人现象。问题最好显示为代码:

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

我正在使用Python 2.7.3。你能猜出 python dad.py 的输出吗?答案是(我希望SO有一个扰流阴影标签) body 1 body 1 spam 3 spam 2 main 3 。所以你能解释一下吗

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. 为什么 body 1 打印两次?

  2. dad.x!= kid.dad.x 怎么样?

  3. 如果我真的需要让两个模块相互导入,如何修改它以获得 kid.dad.x 正确更新?

  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. 因为加载dad.py作为 __ main __ 模块是独立的导入dad.py作为 dad 模块。

  2. 查看我对1的回答。

  3. 如果您必须,请导入 __ main __ 。但总的来说,不要尝试这个。找到完成任务的另一种方法(例如课程)。

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

打印 __ name __ 在dad.py的顶部将说明这一点。

Printing __name__ at the top of dad.py will illustrate this.

这篇关于导入后更改模块变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆