📜  Python __iter__() 和 __next__() |将对象转换为迭代器

📅  最后修改于: 2022-05-13 01:54:54.101000             🧑  作者: Mango

Python __iter__() 和 __next__() |将对象转换为迭代器

在许多情况下,我们需要访问像迭代器这样的对象。一种方法是形成一个生成器循环,但这会延长程序员的任务和时间。 Python通过为此任务提供内置方法 __iter__() 来简化此任务。
__iter__()函数返回给定对象(数组、集合、元组等或自定义对象)的迭代器。它创建了一个对象,可以使用__next__()函数一次访问一个元素,这在处理循环时通常会派上用场。

句法 :

iter(object)
iter(callable, sentinel)
  • Object:必须创建其迭代器的对象。它可以是像列表或元组这样的集合对象,也可以是用户定义的对象(使用 OOPS)。
  • Callable, Sentinel: Callable代表一个可调用对象,sentinel是需要终止迭代的值,sentinel值代表被迭代序列的结束。

例外 :

If we call the iterator after all the elements have 
been iterated, then StopIterationError is raised.

__iter__()函数返回一个遍历给定对象的每个元素的迭代器对象。可以通过 __next__()函数访问下一个元素。在可调用对象和哨兵值的情况下,迭代一直进行,直到找到值或到达元素的末尾。在任何情况下,原始对象都不会被修改。

代码#1:

Python3
# Python code demonstrating
# basic use of iter()
listA = ['a','e','i','o','u']
 
iter_listA = iter(listA)
 
try:
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA))
    print( next(iter_listA)) #StopIteration error
except:
    pass


Python3
# Python code demonstrating
# basic use of iter()
lst = [11, 22, 33, 44, 55]
 
iter_lst = iter(lst)
while True:
    try:
        print(iter_lst.__next__())
    except:
        break


Python3
# Python code demonstrating
# basic use of iter()
 
listB = ['Cat', 'Bat', 'Sat', 'Mat']
 
 
iter_listB = listB.__iter__()
 
try:
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__()) #StopIteration error
except:
    print(" \nThrowing 'StopIterationError'",
                     "I cannot count more.")


Python3
# Python code showing use of iter() using OOPs
 
class Counter:
    def __init__(self, start, end):
        self.num = start
        self.end = end
 
    def __iter__(self):
        return self
 
    def __next__(self):
        if self.num > self.end:
            raise StopIteration
        else:
            self.num += 1
            return self.num - 1
             
             
# Driver code
if __name__ == '__main__' :
     
    a, b = 2, 5
     
    c1 = Counter(a, b)
    c2 = Counter(a, b)
     
    # Way 1-to print the range without iter()
    print ("Print the range without iter()")
     
    for i in c1:
        print ("Eating more Pizzas, counting ", i, end ="\n")
     
    print ("\nPrint the range using iter()\n")
     
    # Way 2- using iter()
    obj = iter(c2)
    try:
        while True: # Print till error raised
            print ("Eating more Pizzas, counting ", next(obj))
    except:
        # when StopIteration raised, Print custom message
        print ("\nDead on overfood, GAME OVER")


输出 :

a
e
i
o
u

代码#2:

Python3

# Python code demonstrating
# basic use of iter()
lst = [11, 22, 33, 44, 55]
 
iter_lst = iter(lst)
while True:
    try:
        print(iter_lst.__next__())
    except:
        break

输出 :

11
22
33
44
55

代码#3:

Python3

# Python code demonstrating
# basic use of iter()
 
listB = ['Cat', 'Bat', 'Sat', 'Mat']
 
 
iter_listB = listB.__iter__()
 
try:
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__())
    print(iter_listB.__next__()) #StopIteration error
except:
    print(" \nThrowing 'StopIterationError'",
                     "I cannot count more.")

输出 :

Cat
Bat
Sat
Mat
 
Throwing 'StopIterationError' I cannot count more.

代码 #4:用户定义的对象(使用 OOPS)

Python3

# Python code showing use of iter() using OOPs
 
class Counter:
    def __init__(self, start, end):
        self.num = start
        self.end = end
 
    def __iter__(self):
        return self
 
    def __next__(self):
        if self.num > self.end:
            raise StopIteration
        else:
            self.num += 1
            return self.num - 1
             
             
# Driver code
if __name__ == '__main__' :
     
    a, b = 2, 5
     
    c1 = Counter(a, b)
    c2 = Counter(a, b)
     
    # Way 1-to print the range without iter()
    print ("Print the range without iter()")
     
    for i in c1:
        print ("Eating more Pizzas, counting ", i, end ="\n")
     
    print ("\nPrint the range using iter()\n")
     
    # Way 2- using iter()
    obj = iter(c2)
    try:
        while True: # Print till error raised
            print ("Eating more Pizzas, counting ", next(obj))
    except:
        # when StopIteration raised, Print custom message
        print ("\nDead on overfood, GAME OVER")
输出
Print the range without iter()
Eating more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Print the range using iter()

Eating more Pizzas, counting  2
Eating more Pizzas, counting  3
Eating more Pizzas, counting  4
Eating more Pizzas, counting  5

Dead on overfood, GAME OVER