python中的迭代器,生成器與裝飾器詳解
迭代器
每一個(gè)可迭代類內(nèi)部都要實(shí)現(xiàn)__iter__()方法,返回一個(gè)迭代類對(duì)象,迭代類對(duì)象則定義了這個(gè)可迭代類如何迭代。
for循環(huán)調(diào)用list本質(zhì)上是是調(diào)用了list的迭代器進(jìn)行迭代。
# 對(duì)list進(jìn)行for循環(huán)本質(zhì)上是調(diào)用了list的迭代器
list = [1,2,3,4]
# for 循環(huán)調(diào)用
for elem in list:
print(elem)
# 迭代器調(diào)用
list_iter = list.__iter__()
while True:
try:
print(next(list_iter))
except StopIteration:
break
實(shí)現(xiàn)一個(gè)自己自定的迭代類,規(guī)定迭代一個(gè)可迭代的數(shù)據(jù)結(jié)構(gòu)為“倒計(jì)時(shí)”模式。
# 可迭代對(duì)象類
class CountDown(object):
def __init__(self,num):
self.num = num
def __iter__(self):
return MyIterator(self.num)
# 迭代類
class MyIterator(object):
def __init__(self,num):
self.NUM= num
self.FINAL = 0
self.now = num
def __iter__(self):
return self
def __next__(self):
step = 1 if self.NUM<self.FINAL else -1
while self.now != self.FINAL:
self.now += step
return self.now - step
raise StopIteration
cd_pos = CountDown(5)
cd_neg = CountDown(-5)
for i,j in zip(cd_pos,cd_neg):
print(f'pos:{i}\tneg:{j}')
生成器
含有yield指令的函數(shù)可以稱為生成器,它可以將函數(shù)執(zhí)行對(duì)象轉(zhuǎn)化為可迭代的對(duì)象。這樣就可以像debug一樣一步一步推進(jìn)函數(shù)??梢詫?shí)現(xiàn)的功能是可以實(shí)現(xiàn)讓函數(shù)內(nèi)部暫停,實(shí)現(xiàn)了程序的異步功能,這樣可以及進(jìn)行該函數(shù)與外部構(gòu)件的信息交互,實(shí)現(xiàn)了系統(tǒng)的解耦。
from collections import Iterable
def f():
pass
# 含有yield指令的函數(shù)可以稱為生成器
def g():
yield()
print(type(f()),isinstance(f(),Iterable))
print(type(g()),isinstance(g(),Iterable))
使用生成器可以降低系統(tǒng)的耦合性
import os
# 生成器是迭代器的一種,讓函數(shù)對(duì)象內(nèi)部進(jìn)行迭代
# 可以實(shí)現(xiàn)讓函數(shù)內(nèi)部暫停,實(shí)現(xiàn)了程序的異步功能,同時(shí)也實(shí)現(xiàn)了解耦。
def my_input():
global str
str = input('input a line')
pass
def my_write():
with open('workfile.txt','w') as f:
while(str):
f.write(str+'\n')
yield()
return
mw = my_write()
while(True):
my_input()
try:
next(mw)
except StopIteration:
pass
if not str:
break
裝飾器
裝飾器封裝一個(gè)函數(shù),并且用這樣或者那樣的方式來修改它的行為。
不帶參數(shù)的裝飾器
# 不帶參數(shù)的裝飾器
from functools import wraps
# 裝飾器封裝一個(gè)函數(shù),并且用這樣或者那樣的方式來修改它的行為。
def mydecorator(a_func):
@wraps(a_func) #聲明這個(gè)注解就可以不重寫傳入的函數(shù),只是調(diào)用的時(shí)候wrap一下。不加的話,a_func函數(shù)可以看作被重寫為wrapTheFunction.
def wrapTheFunction():
print(f"function in {id(a_func)} starts...")
a_func()
print(f"function in {id(a_func)} ends...")
return wrapTheFunction
# 在函數(shù)定義前加入此注解就可以將函數(shù)傳入裝飾器并包裝
@mydecorator
def f():
print('hi')
pass
f()
print(f.__name__)
帶參數(shù)的裝飾器(實(shí)現(xiàn)輸出到自定義的日志文件)
# 帶參數(shù)的裝飾器(實(shí)現(xiàn)輸出到自定義的日志文件)
from functools import wraps
def logit(logfile='out.log'):
def mydecorator2(a_func):
@wraps(a_func)
def wrapTheFunction(*args, **kwargs): # 這個(gè)保證了函數(shù)可以含有任意形參
log_string = a_func.__name__ + " was called"
print(log_string)
# 打開logfile,并寫入內(nèi)容
with open(logfile, 'a') as opened_file:
# 現(xiàn)在將日志打到指定的logfile
opened_file.write(log_string + '\n')
return a_func(*args, **kwargs)
return wrapTheFunction
return mydecorator2
# func group1
@ logit('out1.log')
def func1(str):
print(str)
pass
@ logit('out2.log')
def func2(): pass
func1('I have a foul smell')
func2()
實(shí)現(xiàn)一個(gè)裝飾器類(這樣寫可以簡(jiǎn)化裝飾器函數(shù),并且提高封裝性)
# 帶參數(shù)的裝飾器(實(shí)現(xiàn)輸出到自定義的日志文件)
from functools import wraps
def logit(logfile='out.log'):
def mydecorator2(a_func):
@wraps(a_func)
def wrapTheFunction(*args, **kwargs): # 這個(gè)保證了函數(shù)可以含有任意形參
log_string = a_func.__name__ + " was called"
print(log_string)
# 打開logfile,并寫入內(nèi)容
with open(logfile, 'a') as opened_file:
# 現(xiàn)在將日志打到指定的logfile
opened_file.write(log_string + '\n')
return a_func(*args, **kwargs)
return wrapTheFunction
return mydecorator2
# func group1
@ logit('out1.log')
def func1(str):
print(str)
pass
@ logit('out2.log')
def func2(): pass
func1('I have a foul smell')
func2()
總結(jié)
到此這篇關(guān)于python中的迭代器,生成器與裝飾器詳解的文章就介紹到這了,更多相關(guān)python迭代器,生成器與裝飾器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
django 數(shù)據(jù)庫(kù) get_or_create函數(shù)返回值是tuple的問題
這篇文章主要介紹了django 數(shù)據(jù)庫(kù) get_or_create函數(shù)返回值是tuple的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
從運(yùn)行效率與開發(fā)效率比較Python和C++
今天小編就為大家分享一篇關(guān)于從運(yùn)行效率與開發(fā)效率比較Python和C++,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
基于python全局設(shè)置id 自動(dòng)化測(cè)試元素定位過程解析
這篇文章主要介紹了基于python全局設(shè)置id 自動(dòng)化測(cè)試元素定位過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
PyQT中QTableWidget如何根據(jù)單元格內(nèi)容設(shè)置自動(dòng)寬度
這篇文章主要介紹了PyQT中QTableWidget如何根據(jù)單元格內(nèi)容設(shè)置自動(dòng)寬度問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
如何徹底解決python?NameError:name?'__file__'?is?not?
這篇文章主要給大家介紹了關(guān)于如何徹底解決python?NameError:name?'__file__'?is?not?defined的相關(guān)資料,文中通過圖文將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
python字符串拼接.join()和拆分.split()詳解
這篇文章主要為大家介紹了python字符串拼接.join()和拆分.split(),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11

