0

特定のスコープで他の変数にアクセスできますか? このような:

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でグローバルと非ローカルがどのように機能するかを学びました。今のままで十分だと思いますが、私が求めていることは可能なのだろうか。特に、これについて pep を読んだところ、「特定のスコープで非ローカル」のようなものを作成することを考えていました。しかし、代わりに非ローカルを使用することにしました。非ローカルなしでこれを行う方法があるからですか?それとも、2回書くなど、非ローカルに何らかのトリックがあるのnonlocal nonlocal variableでしょうか?

4

1 に答える 1