python:在赋值之前引用局部变量

nav*_*yad 4 python

这是我的代码:

x = 1
def poi(y):
        # insert line here

def main():
    print poi(1)

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

如果放置4条线,一次一条,代替 # insert line here

 Lines         | Output
---------------+--------------
1. return x    | 1 
2. x = 99      |
   return x    | 99
3. return x+y  | 2 
4. x = 99      | 99  
Run Code Online (Sandbox Code Playgroud)

在上面的行中,似乎在情况1和3中使用了在函数之上声明的全局x

但是,

x = x*y      
return x
Run Code Online (Sandbox Code Playgroud)

这给了

error : local variable 'x' is reference before assignment
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

Joh*_*ooy 5

当Python看到您分配给x它时,强制它成为本地变量名.现在无法x在该函数中看到全局(除非您使用global关键字)

所以

案例1)由于没有本地x,你得到全球

情况2)您正在分配给本地,x因此函数中的所有引用都是本地引用x

案例3)没问题,它x再次使用全局

案例4)与案例2相同


Far*_*hin 4

当你想访问一个全局变量时,你可以通过它的名字来访问它。但如果你想改变它的值,你需要使用关键字global

尝试 :

global x
x = x * y      
return x
Run Code Online (Sandbox Code Playgroud)

在情况 2 中,x 被创建为局部变量,全局 x 从未被使用。

>>> x = 12
>>> def poi():
...   x = 99
...   return x
... 
>>> poi()
99
>>> x
12
Run Code Online (Sandbox Code Playgroud)