Python 3 で「nonlocal」は何をしますか? 質問する

Python 3 で「nonlocal」は何をしますか? 質問する

nonlocalPython 3.x では何が行われますか?


nonlocalOPが必要としているが気付いていないデバッグに関する質問を閉じるには、グローバルスコープではないが外部スコープにある変数を Python で変更することは可能ですか?その代わり。

Python 2は2020年1月1日現在、正式にサポートされていません何らかの理由でPython 2.xのコードベースを保守する必要があり、 に相当するものが必要な場合はnonlocalPython 2.x の nonlocal キーワード

ベストアンサー1

を使わずにこれを比較しますnonlocal:

x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 0

これに を使用するとnonlocal、 の はinner()xにもなりouter()ますx

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 2
# global: 0

を使用すると、適切に「グローバル」な値にglobalバインドされます。x

x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)
        
    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 2

おすすめ記事