我可以访问特定范围内的其他变量吗?像这样:
variable = 'acces with global'
def function1:
variable = 'function 1 variable'
def function2:
variable = 'I really like this name for variable'
def function3:
def access_to_local:
variable = "it's another variable I can access too!"
def access_to_global:
global variable
variable = 'now I have access to my global variable'
def access_to_function2:
nonlocal variable
variable = 'And easy way to change function2 variable'
def access_to_function1:
#nonlocal^2 variable?
variable = 'And how can I get access to variable in
function1?'
这不是生死攸关的问题,我只是个古玩。
我只是学习了python中全局和非局部的工作原理。现在,这已经足够了,但我想知道我的要求是否可行。特别是,我读过政治公众人物关于这个的文章,他们正在考虑做一些类似“特定范围内的非局部”的东西。但是他们决定用非本地的代替。是不是因为有一种方法可以在没有非本地的情况下做到这一点?或者可能有一些非局部的技巧,比如写两次nonlocal nonlocal variable
?你知道吗
不,不能。没有办法指定Python应该跳过嵌套的作用域级别。你知道吗
请注意,使用这么多级别的嵌套并不是很自然;您很少(如果有的话)首先需要使用这么多嵌套。如果在这些罕见的情况下需要访问不同级别的变量,只需使用不同的名称。你知道吗
相关问题 更多 >
编程相关推荐