開始使用免費開始

檢查閉包

你正在教你的姪女學習 Python 程式設計。她正在練習回傳巢狀函式。她覺得自己寫對了,但擔心回傳的函式在被呼叫時拿不到必要的資訊。請向她示範:所有她需要的非區域變數(nonlocal variables)都在新函式的閉包中。

本練習屬於課程

Python 函式寫作

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def return_a_func(arg1, arg2):
  def new_func():
    print('arg1 was {}'.format(arg1))
    print('arg2 was {}'.format(arg2))
  return new_func
    
my_func = return_a_func(2, 17)

# Show that my_func()'s closure is not None
print(my_func.____ is not None)
編輯並執行程式碼