日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python閉包的使用方法_python

作者:程序員班長 ? 更新時(shí)間: 2022-06-12 編程語言

1.閉包的定義和使用

當(dāng)返回的內(nèi)部函數(shù)使用了外部函數(shù)的變量就形成了閉包
閉包可以對外部函數(shù)的變量進(jìn)行保存,還可以提高代碼的可重用性

實(shí)現(xiàn)閉包的標(biāo)準(zhǔn)格式:

  • 1.函數(shù)嵌套
  • 2.內(nèi)部函數(shù)使用外部函數(shù)的變量或參數(shù)
  • 3.外部函數(shù)返回了內(nèi)部函數(shù)
'''
當(dāng)返回的內(nèi)部函數(shù)使用了外部函數(shù)的變量就形成了閉包
閉包可以對外部函數(shù)的變量進(jìn)行保存,還可以提高代碼的可重用性
實(shí)現(xiàn)閉包的標(biāo)準(zhǔn)格式:
? ? 1.函數(shù)嵌套
? ? 2.內(nèi)部函數(shù)使用外部函數(shù)的變量或參數(shù)
? ? 3.外部函數(shù)返回了內(nèi)部函數(shù)
'''
?
# 定義一個閉包
def outer(): ? ?# 外部函數(shù)
? ? n=1
? ? def inner(): ? ?# 內(nèi)部函數(shù)
? ? ? ? print(n)
? ? # 外函數(shù)返回內(nèi)函數(shù)的引用(不用帶括號哈)
? ? return inner
?
outer() # 調(diào)用外函數(shù)不會執(zhí)行內(nèi)函數(shù)
# inner() # 不能直接調(diào)用內(nèi)函數(shù)
ret=outer() # 把內(nèi)函數(shù)的引用給ret
print(ret)
ret()
?
# 閉包的使用
def person(name):
? ? def say(msg):
? ? ? ? print(f'{name} say: ?{msg}')
? ? return say
?
tom=person('Tom')
rose=person('Rose')
tom('Hello')
rose('World')

2.閉包內(nèi)函數(shù)修改外函數(shù)定義的變量(加nonlocal)

def outer():
? ? n=1
? ? def inner():
? ? ? ? nonlocal n ?# 不加會報(bào)錯,列表、字典、元祖不用加
? ? ? ? n=n+10
? ? ? ? print(n)
? ? print(n) ? ?# 輸出1
? ? return inner
?
fun=outer()
fun() ? # 輸出11
fun() ? # 輸出21

原文鏈接:https://kantlee.blog.csdn.net/article/details/122684641

欄目分類
最近更新