Python 閉包例子(1ni)

2021-08-21 12:47:43 字數 636 閱讀 1927

nonloacl pos一定要加,類似globa ,因為在閉包函式裡 執行的時候 在 newpo = pos + step 之後定義了 pos = newpo,

所以python以為我們的pos是函式區域性變數,會報錯unboundlocalerror: local variable 'pos' referenced before assignment

這時候我們應該告訴 python pos是我們閉包函式裡面的環境變數pos

# *_*coding:utf-8 *_*

"""意義在於儲存乙個環境

閉包 = 函式 + 環境 (函式定義時)

""""""

旅行者走路

"""point_x = 0

def tourist(pos):

def go(step):

nonlocal pos

newpo = pos + step

pos = newpo

return newpo

return go

t = tourist(point_x)

print(t(2))

print(t(4))

print(t(6))

Linux 自定義命令列(1ni)

我們在使用伺服器的時候,經常需要遠端控 務器,敲很多的命令,所以我們需要自定義命令列來除去一些複雜繁瑣的工作 1.進入編輯檔案 vim bashrc 然後鍵盤按 shift g 可以跳到檔案最下面 根據vim編輯的話 鍵盤輸入i 這樣就進入編輯模式,也就是insert模式,現在開始正常編輯檔案 我們...

python 閉包 python 閉包

閉包 因為python中函式也可以當作物件,所以如果出現當我們返回乙個函式,而該函式含有外部變數的時候就形成了閉包。閉包的特點 是個巢狀函式 可以獲得非區域性的變數 將函式當作物件返回 看乙個例子會更易理解 def make printer msg msg hi there def printer ...

php閉包使用例子

一.依據閉包實現乙個容器 classdi public function get id class user public function getusername di new di 在此使用了閉包,所以實際上並不會例項化user類,只有在後面get的時候才會例項化 di set a functi...