[英]modify variables outside of function scope from within a function in python 3.5
[英]Modify the function variables from inner function in python
可以獲取並打印外部函數變量a
def outer():
a = 1
def inner():
print a
也可以獲取外部函數數組a
並附加一些內容
def outer():
a = []
def inner():
a.append(1)
print a
但是,當我嘗試增加整數時,這引起了一些麻煩:
def outer():
a = 1
def inner():
a += 1 #or a = a + 1
print a
>> UnboundLocalError: local variable 'a' referenced before assignment
為什么會發生這種情況,如何實現我的目標(增加整數)?
在Python 3中,您可以使用nonlocal
關鍵字執行此操作。 在inner
的開頭執行nonlocal a
,以將a
標記為非本地。
在Python 2中是不可能的。
通常更干凈的方法是:
def outer():
a = 1
def inner(b):
b += 1
return b
a = inner(a)
Python允許很多,但是非局部變量通常可以被認為是“臟的”(這里不做詳細介紹)。
Python 2的解決方法:
def outer():
a = [1]
def inner():
a[0] += 1
print a[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.