Python迭代器下一个方法

2024-09-28 03:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

报告指出:

There should be one-- and preferably only one --obvious way to do it.

现在,考虑到以下情况:

nums = [2, 3, 4]
it = iter(nums)
it.__next__() 
next(it)

最后两种说法有什么不同?它们都返回迭代器中的下一项,而不更改迭代器对象。我发现.__next__()可以用来创建迭代器对象。这是唯一的区别吗


Tags: andto对象only报告itbeone
1条回答
网友
1楼 · 发布于 2024-09-28 03:17:16

next()用于获取序列中的下一项,或者StopIteration异常(如果它位于末尾)

next()通过调用类中定义的__next__()方法来实现这一点

一个例子

class my_list():
    def __init__(self):
        self.data = [1, 2, 3, 4, 5, 6]
        self.pointer = 0

    def __next__(self):
        if self.pointer >= len(self.data):
            self.pointer = 0
            raise StopIteration # to stop the iteration
        item = self.data[self.pointer]
        self.pointer += 1
        return item
    
my_list_obj = my_list()
print(next(my_list_obj)) # use next() function to call __next__()
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj, "empty")) # to print default value at the end

输出

1
2
3
4
5
6
empty

.__next__由用户定义以返回下一个对象

next().__next__的方法包装器

+相同,运算符调用__add__

相关问题 更多 >

    热门问题