python--class:迭代器(iter、next方法)

一、迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代!


二、重新理解:String、list、tuple、dict、set、scv,
其中,list类型的数据没有next()函数,只要先使用__iter()__函数再使用__next()__函数即遵循迭代器协议(解释:__iter__()函数即让数据遵循迭代器协议,生成可迭代对象)
另,for循环的本质:循环所有的对象,都是使用迭代器协议!

例举:
1.证明:list列表类型没有next()函数

2.证明:list()在使用_iter()_函数后,即:遵循迭代器协议,转换成可迭代对象,既可以使用_next()_函数

3.证明:next()函数在没有数据后,即会抛出异常:Stopiteration

4.解释for循环的强大机制

二、自己编写可以产生可迭代对象的类;

需要重写__iter__()、__next__()函数;

举例:


class Foo:
    def __init__(self,n):
        self.n=n

    def __iter__(self):
        return self

    def __next__(self):
        if self.n>20:
            raise StopIteration("完了")
        else:
            self.n+=1
            return self.n


f=Foo(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())

举例:


class Foo1:
    def __init__(self,n):
        self.n=n

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.n)>20:
            raise StopIteration("完了")
        else:
            self.n+="s"
            return self.n


f=Foo1("zhangsan")
print(f.__next__())
print(f.__next__())
print(f.__next__())

猜你喜欢

转载自blog.csdn.net/ak739105231/article/details/86616590