Mik*_*Rev 2 python function global-variables
我有这个代码:
def r():
i += 1
return i
def f():
return x*a
i = 0
a=2
x=3
print f()
print r()
Run Code Online (Sandbox Code Playgroud)
我收到此错误r(),但不是f():
~$ python ~/dev/python/inf1100/test.py
6
Traceback (most recent call last):
File "/home/marius/dev/python/inf1100/test.py", line 18, in <module>
print r()
File "/home/marius/dev/python/inf1100/test.py", line 2, in r
i += 1
UnboundLocalError: local variable 'i' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
为什么可以f()使用函数外部定义的变量,而r()不能使用?
小智 5
那是因为r 重新分配了全局变量i。 f另一方面只是使用它。请记住,它i += 1与 相同i = i + 1。
除非您明确告知,否则 Python 会将函数中使用的所有变量视为局部变量。i此外,由于的局部范围内没有定义变量r,因此会引发错误。
如果你想在函数中重新分配全局变量,你必须输入:
global var
Run Code Online (Sandbox Code Playgroud)
在函数的顶部显式声明var为全局。
因此,为了r工作,应该将其重写为:
def r():
global i
i += 1
return i
Run Code Online (Sandbox Code Playgroud)