简体   繁体   English

使用python导入混淆行为

[英]confusing behavior with python import

Hi, there. 嗨,您好。

I have two files: 我有两个文件:

a.py: a.py:

print('in a')
import b

print('var')
VAR = 1

def p():
    print('{}, {}'.format(VAR, id(VAR)))

if __name__ == '__main__':
    VAR = -1
    p()
    b.p() # Where does this VAR come from?

b.py: b.py:

print('in b')
import a

def p():
    a.p()

I don't understand why there're two different VARs, which is supposed to the same. 我不明白为什么有两种不同的VAR,它们应该是相同的。

If I move the 'main' block to another file, everything works well, ie, there is only one VAR. 如果我将'main'块移动到另一个文件,一切都运行良好,即只有一个VAR。

c.py: c.py:

import a
import b

if __name__ == '__main__':
    a.VAR = -1
    a.p()
    b.p()

So my question is: 所以我的问题是:

Why do the last two lines of a.py print different results? 为什么a.py的最后两行打印出不同的结果?
Don't they print the same VAR variable in a.py? 他们不是在a.py中打印相同的VAR变量吗?

BTW, I'm using python 2.7 on win7. 顺便说一句,我在win7上使用python 2.7。

Thanks. 谢谢。

You might want to read up on global variables ? 您可能想要阅读全局变量 To quote: 报价:

If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. 如果在函数体内的任何位置为变量分配了一个新值,则假定它是一个局部变量。 If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. 如果在函数内部为变量赋予了新值,则该变量隐式为局部变量,您需要将其显式声明为“全局”。

Edit: to elaborate, here's what happens (leaving out c.py for clarity): 编辑:详细说明,这里发生了什么(为了清楚起见, c.pyc.py ):

  1. File a.py is executed. 文件a.py已执行。
  2. File b.py is imported, and in turn imports a.py again. 导入文件b.py ,然后再次导入a.py
  3. Via b's import, VAR is defined in with a value of 1. This ends b`s import. 通过b的导入, VAR定义为值1.这结束了b的导入。
  4. The __main__ part in a.py is executed in its own scope ; a.py__main__部分在其自己的范围内执行; VAR is set to -1 there, and p() is ran: this displays -1, as VAR was just set to. VAR在那里设置为-1,并且运行p() :这显示-1,因为VAR只是设置为。
  5. Then bp() is executed, which in turn runs ap() . 然后执行bp() ,然后运行ap() Because VAR from the perspective of b.py (different scope) still has a value of 1, the print statement just outputs 1. 因为从b.py (不同范围)的角度来看VAR仍然具有值1,所以print语句只输出1。

You'll also notice that the id's are different in both print statements: this is because the VAR 's live in a different scope, and are not connected in any way. 您还会注意到两个打印语句中的ID都不同:这是因为VAR位于不同的范围内,并且没有以任何方式连接。 They are disconnected because __main__ lives in a different, anonymous scope : the scope in which the Python interpreter executes. 它们是断开连接的,因为__main__位于不同的匿名范围内 :Python解释器执行的范围。 This is briefly discussed in the docs . 这在文档中简要讨论过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM