簡體   English   中英

class中沒有__iter__方法的迭代器協議的實現

[英]Implementation of iterator protocol without __iter__ method in class

我已經嘗試使用此代碼來實現迭代器協議,並且一切正常。
理想情況下它不應該因為我沒有實現iter()

class PowerofTwo():
    def __init__(self,maxi):
        self.max = maxi
        self.num = 0     

    def __next__(self):
        if self.num < self.max:
            result = 2 ** self.num
            self.num += 1
            return result
        else:
            raise StopIteration


myObj = PowerofTwo(5)

print(type(myObj)) #print <class '__main__.PowerofTwo'>
print(next(myObj)) #print 1

即使假設__iter__()方法默認可用,如__init__()
但無法理解我如何直接調用next()並首先跳過調用iter(obj)
如果我用列表或其他內置迭代器嘗試同樣的事情,我會收到錯誤消息 object 不是迭代器。

我在這里缺少一些基本的東西嗎?

目前, PowerofTwo是一個迭代器,但它不是一個可迭代對象。 要使其可迭代,您需要定義__iter__以返回具有__next__方法的 object。 在這種情況下, PowerofTwo的實例本身就可以了。

class PowerofTwo:
    def __init__(self,maxi):
        self.max = maxi
        self.num = 0     

    def __iter__(self): return self

    def __next__(self):
        if self.num < self.max:
            result = 2 ** self.num
            self.num += 1
            return result
        else:
            raise StopIteration


for x in PowerofTwo(5):
    print(x)

產出

 1
 2
 4
 8
 16

總是定義

def __iter__(self):
    return self

在定義__next__的 class 中。

list是 class 的一個例子,它的__iter__方法返回另一個class 的實例,即list_iterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM