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

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

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

python中的迭代器,生成器與裝飾器詳解_python

作者:FangNJ ? 更新時間: 2022-04-23 編程語言

迭代器

每一個可迭代類內(nèi)部都要實(shí)現(xiàn)__iter__()方法,返回一個迭代類對象,迭代類對象則定義了這個可迭代類如何迭代。

for循環(huán)調(diào)用list本質(zhì)上是是調(diào)用了list的迭代器進(jìn)行迭代。

# 對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)一個自己自定的迭代類,規(guī)定迭代一個可迭代的數(shù)據(jù)結(jié)構(gòu)為“倒計(jì)時”模式。

# 可迭代對象類
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í)行對象轉(zhuǎn)化為可迭代的對象。這樣就可以像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ù)對象內(nèi)部進(jìn)行迭代
# 可以實(shí)現(xiàn)讓函數(shù)內(nèi)部暫停,實(shí)現(xiàn)了程序的異步功能,同時也實(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   

裝飾器

裝飾器封裝一個函數(shù),并且用這樣或者那樣的方式來修改它的行為。

不帶參數(shù)的裝飾器

# 不帶參數(shù)的裝飾器
from functools import wraps
# 裝飾器封裝一個函數(shù),并且用這樣或者那樣的方式來修改它的行為。
def mydecorator(a_func):
    @wraps(a_func)  #聲明這個注解就可以不重寫傳入的函數(shù),只是調(diào)用的時候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):   # 這個保證了函數(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)一個裝飾器類(這樣寫可以簡化裝飾器函數(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):   # 這個保證了函數(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é)

原文鏈接:https://blog.csdn.net/FangNJ/article/details/122986008

欄目分類
最近更新