Python裝飾器用法與知識點小結
本文實例講述了Python裝飾器用法與知識點。分享給大家供大家參考,具體如下:
(1)裝飾器含參數,被裝飾函數不含(含)參數
實例代碼如下:
import time
# 裝飾器函數
def wrapper(func):
def done(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print('the func run time is %s' % (stop_time - start_time))
return done
# 被裝飾函數1
@wrapper
def test1():
time.sleep(1)
print("in the test1")
# 被裝飾函數2
@wrapper
def test2(name): #1.test2===>wrapper(test2) 2.test2(name)==dome(name)
time.sleep(2)
print("in the test2,the arg is %s"%name)
# 調用
test1()
test2("Hello World")
(2)裝飾器含有參數,被裝飾函數含(不含)參數
import time
user,passwd = 'admin','admin'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("ldap鏈接")
return wrapper
return outer_wrapper
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page"
print(home()) #wrapper()
bbs()
總結:
(1)裝飾器實質為函數內嵌,返回函數地址。
(2)裝飾器帶參數與不帶參數相比裝飾器帶參數的多了一層函數定義用于接收裝飾器中傳遞的參數,其余基本相同。
(3)先驗證裝飾器中的參數,在驗證普通函數的參數
小知識:
列表生產式:[i for i in range(5)]---->[0,1,2,3,4,5]
生成器與迭代器:
第一種方式通過括號的方式生成
生成器:()---(i for i in range(5)) ==>generator
這種一邊循環(huán)一邊計算的機制,稱為生成器:generator。
生成器只有在調用時才會生成相應的數據,只記錄當前位置。
只有一個__next__()方法
第二種方式通過yield生成
在函數中使用yield即可將一個函數變?yōu)橐粋€生成器
迭代器:
直接作用于for循環(huán)的數據類型:
一類是集合數據類型,如list、tuple、dict、set、str等;
一類是generator,包括生成器和帶yield的generator function。
直接作用于for循環(huán)的對象統(tǒng)稱為可迭代對象:Iterable。
可以使用isinstance()判斷一個對象是否是Iterable對象
from collections import Iterable isinstance([], Iterable)=========true
*可以被next()函數調用并不斷返回下一個值的對象稱為迭代器:Iterator。
可以使用isinstance()判斷一個對象是否是Iterator對象:
>>> from collections import Iterator >>> isinstance((x for x in range(10)), Iterator) ======>True
生成器都是Iterator對象,但list、dict、str雖然是Iterable,卻不是Iterator。
把list、dict、str等Iterable變成Iterator可以使用iter()函數:
例如:iter([])<====迭代器
Python的Iterator對象表示的是一個數據流,Iterator對象可以被next()函數調用并不斷返回下一個數據,直到沒有數據時拋出StopIteration錯誤??梢园堰@個數據流看做是一個有序序列,但我們卻不能提前知道序列的長度,只能不斷通過next()函數實現按需計算下一個數據,所以Iterator的計算是惰性的,只有在需要返回下一個數據時它才會計算。
Iterator甚至可以表示一個無限大的數據流,例如全體自然數。而使用list是永遠不可能存儲全體自然數的。
小結:
凡是可作用于for循環(huán)的對象都是Iterable類型;
凡是可作用于next()函數的對象都是Iterator類型,它們表示一個惰性計算的序列;
集合數據類型如list、dict、str等是Iterable但不是Iterator,不過可以通過iter()函數獲得一個Iterator對象。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。

