網站首頁 編程語言 正文
迭代器
每一個可迭代類內部都要實現__iter__()方法,返回一個迭代類對象,迭代類對象則定義了這個可迭代類如何迭代。
for循環調用list本質上是是調用了list的迭代器進行迭代。
# 對list進行for循環本質上是調用了list的迭代器 list = [1,2,3,4] # for 循環調用 for elem in list: print(elem) # 迭代器調用 list_iter = list.__iter__() while True: try: print(next(list_iter)) except StopIteration: break
實現一個自己自定的迭代類,規定迭代一個可迭代的數據結構為“倒計時”模式。
# 可迭代對象類 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指令的函數可以稱為生成器,它可以將函數執行對象轉化為可迭代的對象。這樣就可以像debug一樣一步一步推進函數??梢詫崿F的功能是可以實現讓函數內部暫停,實現了程序的異步功能,這樣可以及進行該函數與外部構件的信息交互,實現了系統的解耦。
from collections import Iterable def f(): pass # 含有yield指令的函數可以稱為生成器 def g(): yield() print(type(f()),isinstance(f(),Iterable)) print(type(g()),isinstance(g(),Iterable))
使用生成器可以降低系統的耦合性
import os # 生成器是迭代器的一種,讓函數對象內部進行迭代 # 可以實現讓函數內部暫停,實現了程序的異步功能,同時也實現了解耦。 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
裝飾器
裝飾器封裝一個函數,并且用這樣或者那樣的方式來修改它的行為。
不帶參數的裝飾器
# 不帶參數的裝飾器 from functools import wraps # 裝飾器封裝一個函數,并且用這樣或者那樣的方式來修改它的行為。 def mydecorator(a_func): @wraps(a_func) #聲明這個注解就可以不重寫傳入的函數,只是調用的時候wrap一下。不加的話,a_func函數可以看作被重寫為wrapTheFunction. def wrapTheFunction(): print(f"function in {id(a_func)} starts...") a_func() print(f"function in {id(a_func)} ends...") return wrapTheFunction # 在函數定義前加入此注解就可以將函數傳入裝飾器并包裝 @mydecorator def f(): print('hi') pass f() print(f.__name__)
帶參數的裝飾器(實現輸出到自定義的日志文件)
# 帶參數的裝飾器(實現輸出到自定義的日志文件) from functools import wraps def logit(logfile='out.log'): def mydecorator2(a_func): @wraps(a_func) def wrapTheFunction(*args, **kwargs): # 這個保證了函數可以含有任意形參 log_string = a_func.__name__ + " was called" print(log_string) # 打開logfile,并寫入內容 with open(logfile, 'a') as opened_file: # 現在將日志打到指定的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()
實現一個裝飾器類(這樣寫可以簡化裝飾器函數,并且提高封裝性)
# 帶參數的裝飾器(實現輸出到自定義的日志文件) from functools import wraps def logit(logfile='out.log'): def mydecorator2(a_func): @wraps(a_func) def wrapTheFunction(*args, **kwargs): # 這個保證了函數可以含有任意形參 log_string = a_func.__name__ + " was called" print(log_string) # 打開logfile,并寫入內容 with open(logfile, 'a') as opened_file: # 現在將日志打到指定的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()
總結
原文鏈接:https://blog.csdn.net/FangNJ/article/details/122986008
相關推薦
- 2022-04-18 WPF使用代碼創建數據模板DataTemplate_實用技巧
- 2022-04-12 【debug】PytorchStreamReader failed reading zip arch
- 2022-04-01 .Net使用SuperSocket框架實現WebSocket后端_實用技巧
- 2023-01-20 python-try-except:pass的用法及說明_python
- 2022-10-06 C++?pimpl機制詳細講解_C 語言
- 2022-08-15 Golang通過包長協議處理TCP粘包的問題解決_Golang
- 2023-11-16 【電腦Windows日常】解決Windows11 無法顯示office圖標的問題
- 2023-07-16 uniapp 調用拍照組件
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支