2024-09-28 03:17:16 发布
网友
报告指出:
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__()可以用来创建迭代器对象。这是唯一的区别吗
.__next__()
next()用于获取序列中的下一项,或者StopIteration异常(如果它位于末尾)
next()
StopIteration
next()通过调用类中定义的__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()是.__next__的方法包装器
与+相同,运算符调用__add__
+
__add__
next()
用于获取序列中的下一项,或者StopIteration
异常(如果它位于末尾)next()
通过调用类中定义的__next__()
方法来实现这一点一个例子
输出
.__next__
由用户定义以返回下一个对象next()
是.__next__
的方法包装器与
+
相同,运算符调用__add__
相关问题 更多 >
编程相关推荐