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



我可以访问特定范围内的其他变量吗?喜欢这个:

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 应跳过嵌套范围级别。

请注意,使用这么多级别的嵌套并不是很自然的;你很少(如果有的话)首先需要使用这么多的嵌套。如果您需要在极少数情况下访问不同级别的变量,只需使用不同的名称即可。

最新更新