给出以下代码:
def A() :
b = 1
def B() :
# I can access 'b' from here.
print( b )
# But can i modify 'b' here? 'global' and assignment will not work.
B()
A()
Run Code Online (Sandbox Code Playgroud)
对于B()函数变量中的代码,b在外部作用域中,但不在全局作用域中.是否可以b从B()函数内修改变量?当然我可以从这里读取它print(),但是如何修改呢?
假设我有以下python代码:
def outer():
string = ""
def inner():
string = "String was changed by a nested function!"
inner()
return string
Run Code Online (Sandbox Code Playgroud)
我想调用outer()来返回"String被嵌套函数改变了!",但我得到了"".我得出结论,Python认为该行string = "string was changed by a nested function!"是对inner()本地新变量的声明.我的问题是:如何告诉Python它应该使用outer()字符串?我不能使用global关键字,因为字符串不是全局的,它只是在外部范围内.想法?
这一点Python不起作用:
def make_incrementer(start):
def closure():
# I know I could write 'x = start' and use x - that's not my point though (:
while True:
yield start
start += 1
return closure
x = make_incrementer(100)
iter = x()
print iter.next() # Exception: UnboundLocalError: local variable 'start' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我知道如何解决这个错误,但请耐心等待:
这段代码工作正常:
def test(start):
def closure():
return start
return closure
x = test(999)
print x() # prints 999
Run Code Online (Sandbox Code Playgroud)
为什么我可以读取start闭包内的变量而不是写入它?导致这种start变量处理的语言规则是什么?
更新:我发现这个SO帖子相关(答案不仅仅是问题):读/写Python闭包