简体   繁体   English

我可以在python3.4中访问不同于非本地变量或全局变量的变量吗?

[英]Can I get access to variable different from nonlocal or global in python3.4?

Can I access to other variable in specific scope? 我可以访问特定范围内的其他变量吗? Like this: 像这样:

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?'

It's not life or death question, I'm just curios. 这不是生死攸关的问题,我只是古玩。 I just learn how global and nonlocal work in python. 我只是学习python中的全局和非本地工作方式。 Right now, it's definitely enough, but I wonder if what I'm asking is possible. 现在,这肯定够了,但是我想知道我要问的事情是否可能。 Especially, that I read pep about this, and they was thinking about making something like "nonlocal in specific scope". 尤其是,我读到有关此的鼓舞士气,他们正在考虑做出类似“特定范围内的非本地性”的内容。 But they decided to use nonlocal instead. 但是他们决定改用非本地的。 Is it because there is way of doing this without nonlocal? 是因为有没有非本地的方法吗? Or maybe there is some trick with nonlocal, like writing it two times nonlocal nonlocal variable ? 或者,也许有一些关于非本地的技巧,例如将其编写两次nonlocal nonlocal variable

No, you can't. 不,你不能。 There is no way to specify that Python should skip a nested scope level. 无法指定Python应该跳过嵌套的作用域级别。

Note that using this many levels of nesting is not really natural; 请注意,使用这么多级别的嵌套并不是很自然。 you rarely, if ever, will need to use this much nesting in the first place. 您很少(如果有的话)首先需要使用这么多的嵌套。 Just use different names if you need to access variables at different levels in those rare cases. 如果在极少数情况下需要访问不同级别的变量,只需使用不同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM