|
global 定義全局變量,必須先聲明,在使用 例如:global a #聲明全局變量 a = a+1 locals() 獲取本函數(shù)作用域中的局部變量(函數(shù)即變量) nonlocal 必須在整個嵌套函數(shù)作用域內(nèi)定義局部變量,獲取上層函數(shù)的變量 例如: 1. def test(): a = 1 def test1(): nonlocal a #必須先聲明 a = a+1 print (a) return test1 t = test() t() 打印a = 2 2. def test(): 打印a = 2 如果nonlocal的外層函數(shù)沒有定義局部變量,則報錯
|
|
|