日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Day05:装饰器,三元表达式,函数的递归,匿名/内置函数,迭代器,模块,开发目录...

發布時間:2025/3/15 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Day05:装饰器,三元表达式,函数的递归,匿名/内置函数,迭代器,模块,开发目录... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

上節課復習:
1.函數的對象
??? 函數可以被當作數據取處理
2.函數嵌套
??? 嵌套調用:在調用一個函數時,函數體代碼又調用了其他函數
??? 嵌套定義:在一個函數內部又定義了另一個函數

1 def foo() 2 def inner(): 3 pass 4 return inner #拿到inner的內存地址 5 f=foo() #foo全局變量可以通過返回的inner地址調用inner

3.名稱空間與作用域
??? 名稱空間:存放名字與值的內存地址綁定關系的地方
??? x=1
??? x
??? 內置名稱空間
??? 全局名稱空間
??? 局部名稱空間
??? 查找順序:當前所在的位置往上依次查找
??? 全局作用范圍:全局存活,全局有效

1 def f1(): 2 def f1_inner1(): 3 def f1_inner2(): 4 pass 5 def f2(): 6 def f2_inner1(): 7 def f2_inner2(): 8 pass

??? 局部作用范圍:臨時存活,局部有效
??? 強調:作用域關系在函數定義階段就已經固定死了,與調用關系無關
4.閉包函數
??? 閉:封閉在函數內部,即定義在函數內部的函數
??? 包:該內部包含對外部函數作用域名字的引用

1 x=1 2 def outter(): 3 x=111 4 def inner(): 5 print (x) 6 return inner 7 f=outter()

今日內容:
1.裝飾器剩余(*****)
??? 有參裝飾器
2.三元表達式,列表生成式,字典生成式(*****)
3.函數的遞歸調用,二分法(*****)
4.匿名函數lambda+內置函數(*****)
5.迭代器(****)
6.模塊的使用(*****)
7.軟件開發的目錄規范(*****)

一.裝飾器
??? 1.定義:器指的是工具,裝飾指的是為被裝飾的對象添加新功能
??????? 裝飾器即使為被裝飾對象添加新功能的工具
??????? 裝飾器本身可以是任意可調用的對象
??????? 被裝飾對象本身也可以是任意可調用的對象
??? 2.開放封閉原則:
??? 軟件一旦上線以后,就應該對修改(源代碼+調用方式)封閉,對擴展開放的
??????? 1.不修改被裝飾對象的源代碼
??????? 2.不修改被裝飾對象的調用方式
??? 3.如何實現

1 #原先的調用方式 2 import time 3 def index(): 4 print('welcom to index page') 5 time.sleep(1) 6 start=time.time() 7 index() 8 stop=time.time() 9 print ('run time is %s' %(stop - start))

輸出:

welcom to index page
run time is 1.0005970001220703

1 import time 2 def index(): 3 print('welcom to index page') 4 time.sleep(1) 5 def wrapper(func): 6 start=time.time() 7 func() 8 stop=time.time() 9 print ('run time is %s' %(stop - start)) 10 11 wrapper(index)

輸出:

welcom to index page
run time is 1.000910758972168

1 import time 2 def index(): 3 print('welcom to index page') 4 time.sleep(1) 5 def outter(func): 6 def wrapper(): 7 start=time.time() 8 func() 9 stop=time.time() 10 print ('run time is %s' %(stop - start)) 11 return wrapper 12 index=outter(index) 13 index()

輸出:
welcom to index page
run time is 1.0008034706115723

1 #加了裝飾器,目的是不改變原來的調用方式,對使用者是透明的 2 import time 3 def index(): 4 print('welcom to index page') 5 time.sleep(1) 6 def outter(func): 7 def wrapper(*args,**kwargs): 8 start=time.time() 9 res=func(*args,**kwargs) 10 stop=time.time() 11 print ('run time is %s' %(stop - start)) 12 return res 13 return wrapper 14 index=outter(index) 15 index() #wrapper() 為實際調用函數,需模擬原先的內部邏輯

輸出:

welcom to index page
run time is 1.0013582706451416

1 #加了裝飾器,目的是不改變原來的調用方式,對使用者是透明的 2 import time 3 def index(): 4 print('welcom to index page') 5 time.sleep(1) 6 def home(name): 7 print('welcom to home page') 8 time.sleep(2) 9 def outter(func): 10 def wrapper(*args,**kwargs): 11 start=time.time() 12 res=func(*args,**kwargs) 13 stop=time.time() 14 print ('run time is %s' %(stop - start)) 15 return res 16 return wrapper 17 index=outter(index) 18 home=outter(home) 19 index() #wrapper() 為實際調用函數,需模擬原先的內部邏輯 20 home('andy') #wrapper('andy')

welcom to index page
run time is 1.0008716583251953
welcom to home page
run time is 2.0003538131713867

#加了裝飾器,目的是不改變原來的調用方式,對使用者是透明的 import timedef timmer(func):def wrapper(*args,**kwargs):start=time.time()res=func(*args,**kwargs)stop=time.time()print ('run time is %s' %(stop - start))return resreturn wrapper @timmer #index=timer(index) def index():print('welcom to index page')time.sleep(1) @timmer #home=timer(home) def home(name):print('welcom to home page')time.sleep(2)return 123index() #wrapper() 為實際調用函數,需模擬原先的內部邏輯 res=home('andy') #wrapper('andy')


輸出:

welcom to index page
run time is 1.0023157596588135
welcom to home page
run time is 2.000333309173584

1 #模板 2 def outter(func): 3 def inner(*args,**kwargs): 4 res=func(*args,**kwargs) 5 return res 6 return res

輸出:

1 #認證功能裝飾器實現 2 import time 3 4 current_userinfo={'user':None} 5 def outter(func): # func為被裝飾對象 6 def wrapper(*args,**kwargs): 7 if current_userinfo['user']: #判斷是否已登陸 8 return func(*args,**kwargs) 9 else: 10 user=input('please input username:').strip() 11 pwd=input('please input password:').strip() 12 if user == 'andy' and pwd =='123': 13 print('login successfully') 14 #保存登陸狀態 15 current_userinfo['user']=user 16 res=func(*args,**kwargs) 17 return res 18 else: 19 print ('user or password wrong') 20 return wrapper 21 @outter #index=outter(index) 22 def index(): 23 print('welcom to index page') 24 time.sleep(1) 25 @outter #home=outter(home) 26 def home(name): 27 print('welcom to home page') 28 time.sleep(2) 29 return 123 30 31 index() #wrapper() 為實際調用函數,需模擬原先的內部邏輯 32 res=home('andy') #wrapper('andy')

輸出:

please input username:andy
please input password:123
login successfully
welcom to index page
welcom to home page

1 #添加多個裝飾器 2 import time 3 current_userinfo={'user':None} 4 def timmer(func): #func=wrapper1 5 def wrapper2(*args,**kwargs): 6 print('wrapper2 run...') 7 start=time.time() 8 res=func(*args,**kwargs) #調到outter內的wrapper1 9 stop=time.time() 10 print ('run time is %s' %(stop - start)) 11 return res 12 return wrapper2 13 14 def outter(func): # func=最原始的index 15 def wrapper1(*args,**kwargs): 16 print('wrapper1 run...') 17 if current_userinfo['user']: #判斷是否已登陸 18 return func(*args,**kwargs) 19 else: 20 user=input('please input username:').strip() 21 pwd=input('please input password:').strip() 22 if user == 'andy' and pwd =='123': 23 print('login successfully') 24 #保存登陸狀態 25 current_userinfo['user']=user 26 res=func(*args,**kwargs) #調用最原始的index 27 return res 28 else: 29 print ('user or password wrong') 30 return wrapper1 31 @timmer #index=timmer(wrapper1),將下方返回的wrapper1傳入 32 @outter #outter(最原始的index) ==> wrapper1=outter(最原始的index) 33 def index(): 34 print('welcom to index page') 35 time.sleep(1) 36 index() #index==>wrapper2


輸出:

?wrapper2 run...
wrapper1 run...
please input username:andy
please input password:123
login successfully
welcom to index page
run time is 8.713418006896973

1 #添加多個裝飾器 2 import time 3 current_userinfo={'user':None} 4 def timmer(func): #func=wrapper1 5 def wrapper2(*args,**kwargs): 6 print('wrapper2 run...') 7 start=time.time() 8 res=func(*args,**kwargs) #調到outter內的wrapper1 9 stop=time.time() 10 print ('run time is %s' %(stop - start)) 11 return res 12 return wrapper2 13 14 def outter(func): # func=最原始的index 15 def wrapper1(*args,**kwargs): 16 print('wrapper1 run...') 17 if current_userinfo['user']: #判斷是否已登陸 18 return func(*args,**kwargs) 19 else: 20 user=input('please input username:').strip() 21 pwd=input('please input password:').strip() 22 if user == 'andy' and pwd =='123': 23 print('login successfully') 24 #保存登陸狀態 25 current_userinfo['user']=user 26 res=func(*args,**kwargs) #調用最原始的index 27 return res 28 else: 29 print ('user or password wrong') 30 return wrapper1 31 # 可以連續寫多個裝飾器,處于最頂層的裝飾器先執行,解釋語法自下而上,執行時則自上而下 32 @outter # 33 @timmer # 34 def index(): 35 print('welcom to index page') 36 time.sleep(1) 37 index() #index==>wrapper2

輸出:

wrapper1 run...
please input username:andy
please input password:123
login successfully
wrapper2 run...
welcom to index page
run time is 1.0009920597076416

1 #有參裝飾器 2 #認證功能裝飾器實現 3 import time 4 5 current_userinfo={'user':None} 6 def auth(engine='file'): 7 def outter(func): # func為被裝飾對象 8 def wrapper(*args,**kwargs): 9 if engine == 'file': 10 if current_userinfo['user']: #判斷是否已登陸 11 return func(*args,**kwargs) 12 else: 13 user=input('please input username:').strip() 14 pwd=input('please input password:').strip() 15 if user == 'andy' and pwd =='123': 16 print('login successfully') 17 #保存登陸狀態 18 current_userinfo['user']=user 19 res=func(*args,**kwargs) 20 return res 21 else: 22 print ('user or password wrong') 23 elif engine == 'mysql': 24 print ('mysql 的認證機制') 25 elif engine == 'ldap': 26 print ('ldap 的認證機制') 27 else: 28 print('不支持該engine') 29 return wrapper 30 return outter 31 @auth(engine='mysql') 32 #@outter #index=outter(index) #index=wrapper 33 def index(): 34 print('welcom to index page') 35 time.sleep(1) 36 @auth(engine='file') 37 def home(name): 38 print('welcom to home page') 39 time.sleep(2) 40 return 123 41 42 index() #wrapper() 為實際調用函數,需模擬原先的內部邏輯 43 res=home('andy') #wrapper('andy')

輸出:
mysql 的認證機制
please input username:andy
please input password:123
login successfully
welcom to home page

1 #加了裝飾器,目的是不改變原來的調用方式,對使用者是透明的 2 import time 3 from functools import wraps 4 5 def timmer(func): 6 @wraps(func) 7 def wrapper(*args,**kwargs): 8 start=time.time() 9 res=func(*args,**kwargs) 10 stop=time.time() 11 print ('run time is %s' %(stop - start)) 12 return res 13 #wrapper.__doc__=func.__doc__ 14 #wrapper.__name__=func.__name__ 15 return wrapper 16 @timmer #index=timer(index) 17 def index(): 18 """ 19 這是一個index函數 20 :return 21 """ 22 print('welcom to index page') 23 time.sleep(1) 24 return 123 25 print(help(index)) 26 #print(index.__name__)

輸出:
Help on function index in module __main__:

index()
??? 這是一個index函數
??? :return

None

1 #三元表達式 2 def max2(x,y): 3 if x>y: 4 return x 5 else: 6 return y 7 res=max2(1,2) 8 9 res=True if x>y else False 10 print (res) 11 12 #列表生成式 13 l=[] 14 for i in range(10): 15 l.append(i) 16 print(l) 17 18 l1=[i for i in range(10)] 19 print(l1) 20 21 #字典生成式 22 s={i:i for i in range(10) if i>3} 23 print (s) 24 25 26 info=[ 27 ['name','alex'], 28 ('age',18) 29 ['sex','male'] 30 ] 31 d={item[0]:item[1] for item in info} 32 print(d) 33 34 d={k.upper():v for k,v in d.items()} 35 print(d)

二.函數遞歸
??? 函數遞歸調用,在調用一個函數的過程中又直接或間接地調用了自己稱之為函數的遞歸調用
??? 本質就是一個重復的過程,遞歸必須要滿足兩個階段
??? 1.回溯:一層一層地遞歸調用下去
??? 2.遞推:遞歸必須要有一個明確的結束條件,在滿足該條件下終止遞歸,往回一層一層地結束調用
??? 遞歸vs while循環
??? 遞歸只需要把控住結束或進入遞歸的條件即可,至于循環次數無需考慮

1 #直接遞歸 2 def foo(n): 3 print('from foo',n) 4 foo(n+1) 5 foo(0) 6 7 #間接遞歸 8 def bar(): 9 print('from bat') 10 11 def foo(): 12 print('from foo') 13 bar() 14 foo()

?

1 def age(n): 2 if n==1: 3 return 18 4 return age(n-1) +2 5 6 print(age(5))

輸出:26

1 l=[1,[2,[3,]]] 2 def tell(l): 3 for item in l: 4 if type(item) is not list: 5 print(item) 6 else: 7 #再次調用本身的邏輯,傳入item 8 tell(item) 9 tell(l)

輸出:

1
2
3

1 nums=[3,11,13,15,23,27,43,51,72,81,93,101] 2 #算法,就是高效解決某個具體問題的方法 3 #find_num=23 4 def binary_search(nums,find_num): 5 print(nums) 6 if len(nums) == 0: 7 print('not exists') 8 return 9 mid_index=len(nums) // 2 10 if find_num>nums[mid_index]: 11 nums=nums[mid_index+1:] 12 binary_search(nums,find_num) 13 elif find_num < nums[mid_index]: 14 nums=nums[:mid_index] 15 binary_search(nums,find_num) 16 else: 17 print('find it') 18 binary_search(nums,99) 19 binary_search(nums,3)

輸出:
[3, 11, 13, 15, 23, 27, 43, 51, 72, 81, 93, 101]
[51, 72, 81, 93, 101]
[93, 101]
[93]
[]
not exists
[3, 11, 13, 15, 23, 27, 43, 51, 72, 81, 93, 101]
[3, 11, 13, 15, 23, 27]
[3, 11, 13]
[3]
find it

三.匿名函數

  匿名函數lambda:只用一次以后不會再用了

(lambda x,y:x+y)(4,5)

輸出:9

#原方法 salaries={'andy':1000,'alex':2000,'lily':400 } def func(k):return salaries[k] print(max(salaries,key=func)) #使用匿名函數 salaries={'andy':1000,'alex':2000,'lily':400 }print(max(salaries,key=lambda x:salaries[x]))

輸出:alex

1 num=[3,1,4,9] 2 l=sorted(num) 3 print (l) 4 l=sorted(num,reverse=True) 5 print (l)

輸出:
[1, 3, 4, 9]
[9, 4, 3, 1]

1 salaries={ 2 'andy':1000, 3 'alex':2000, 4 'lily':400 5 } 6 7 print(sorted(salaries,key=lambda x:salaries[x]))

輸出:

['lily', 'andy', 'alex']

1 #了解map,reduce,filter 2 #map映射 3 names=['andy','alex','tom'] 4 res=map(lambda x:x+'_dsb',names) 5 print (list(res))

輸出:

['andy_dsb', 'alex_dsb', 'tom_dsb']

1 #filter過濾 2 names=['andy_dsb', 'alex_dsb', 'tom_dsb'] 3 res=filter(lambda x:x.endswith('dsb'),names) 4 print (res) 5 for item in res: 6 print(item) 7 l=[name for name in names if name.endswith('dsb')] 8 print(l)

輸出:

<filter object at 0x0000023BB55D6A58>
andy_dsb
alex_dsb
tom_dsb
['andy_dsb', 'alex_dsb', 'tom_dsb']

1 #reduce合并 2 from functools import reduce 3 l=['a','b','c','d','e'] 4 res=reduce(lambda x,y:x+y,l,'AAA') 5 print(res)

輸出:

AAAabcde

1 from functools import reduce 2 l=['a','b','c','d','e'] 3 res=reduce(lambda x,y:x+y,l) 4 print(res)

輸出:

abcde

四.模塊
1.什么是模塊
??? 模塊就是一系列功能的集合體,
??? 模塊分為三大類:
??????? 1.自定義模塊
??????? 2.內置模塊:time,sys
??????? 3.第三方的模塊
??? 模塊的表現形式有
??????? 1.使用python編寫的.py文件
??????? 2.已被編譯為共享庫或DLL的C或C++擴展
??????? 3.把一系列模塊組織到一起的文件夾(注:文件夾下有一個__init__.py文件,該文件夾稱之為包)
??????? 4.使用C編寫并鏈接到python解釋器的內置模塊
2.為何要用模塊
??? 1.可以拿來內置或第三方的模塊,然后直接使用,這種拿來主義,會極大地提高開發效率
??? 2.將程序中公用的一些功能組織到一個文件中,然后程序個部分功能可以重用該文件的功能
??? 優點是減少代碼冗余,增強程序的組織結構性和可維護性
3.如何用模塊
??? 一個py文件就是一個模塊
4.首次導入模塊會發生三件事:
??? 1.創建一個模塊spam.py的名稱空間
??? 2.執行模塊對應的spam.py,將產生的名字丟到模塊的名稱空間
??? 3.在當前執行的名稱空間中拿到一個名字spam,該名字就是指向模塊spam.py的名稱空間的內存地址
??? import spam #spam=spam.py
??? import spam #后續的導入執行引用之前導入的結果spam=spam.py名稱空間的內存地址
??? print (spam.money)
兩種導入方式的優缺點:
from import vs import
相同點:函數的作用域關系在定義階段就規定死了,與調用位置無關
from import
優點:可以不用加前綴而直接引用名字,更簡潔
缺點:容易與當前執行文件中的名字沖突
import
優點:指名道姓跟某一個名稱空間要名字,肯定不會與當前名稱空間的名字相沖突
缺點:必須加上前綴

?

#一個python文件有兩種用途
1.可以執行: __name__ =='__main__'
2.可以被當作模塊導入:__name__=='模塊名'
模塊的搜索優先級:
1.內存
2.內置的模塊
3.sys.path

1 import sys 2 print(sys.path)

?

轉載于:https://www.cnblogs.com/dingchuan/p/9357030.html

總結

以上是生活随笔為你收集整理的Day05:装饰器,三元表达式,函数的递归,匿名/内置函数,迭代器,模块,开发目录...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。