新聞中心
(推薦操作系統(tǒng):windows7系統(tǒng)、python 3.9.1、DELL G3電腦。)

成都創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比紅橋網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式紅橋網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋紅橋地區(qū)。費用合理售后完善,十載實體公司更值得信賴。
1、如果你想讓你的生成器暴露外部狀態(tài)給用戶, 別忘了你可以簡單的將它實現(xiàn)為一個類,然后把生成器函數(shù)放到 ____iter__()__() 方法中過去。比如:
from collections import deque class linehistory: def __init__(self, lines, histlen=3): self.lines = lines self.history = deque(maxlen=histlen) def __iter__(self): for lineno, line in enumerate(self.lines, 1): self.history.append((lineno, line)) yield line def clear(self): self.history.clear()
2、為了使用這個類,你可以將它當做是一個普通的生成器函數(shù)。然而,由于可以創(chuàng)建一個實例對象,于是你可以訪問內(nèi)部屬性值,比如 history 屬性或者是 clear() 方法。代碼示例如下:
with open('somefile.txt') as f:
lines = linehistory(f)
for line in lines:
if 'python' in line:
for lineno, hline in lines.history:
print('{}:{}'.format(lineno, hline), end='')
以上就是python使用__iter__()展現(xiàn)外部狀態(tài)的方法,希望能對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文題目:創(chuàng)新互聯(lián)Python教程:python如何使用__iter__()展現(xiàn)外部狀態(tài)
標題路徑:http://www.dlmjj.cn/article/ccospgs.html


咨詢
建站咨詢
