Python nonlocal 關鍵字

實例

在函數內部創建一個函數,該函數使用變量 x 作為非局部變量:

def myfunc1():
  x = "Bill"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2() 
  return x
print(myfunc1())

運行實例

定義和用法

nonlocal 關鍵字用于在嵌套函數內部使用變量,其中變量不應屬于內部函數。

請使用關鍵字 nonlocal 聲明變量不是本地變量。

更多實例

實例

與上例相同,但不使用 nonlocal 關鍵字:

def myfunc1():
  x = "Bill"
  def myfunc2():
    x = "hello"
  myfunc2() 
  return x
print(myfunc1())

運行實例

相關頁面

關鍵字 global 用于創建全局變量。