欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python:自定义类中迭代行为的实现

程序员文章站 2022-03-15 19:38:32
...

python迭代器-csdn博客

Python 中 Iterator和Iterable的区别


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : cat
# @date   : 2017/6/23.


class Squares:
    """
    单(个活跃的)迭代器的实现
    """

    def __init__(self, start, stop):
        self.value = start - 1
        self.stop = stop
        print("s1 init ---- ", start, stop)

    def __iter__(self):
        print('s1: _iter_')
        return self

    def __next__(self):
        print("s1: _next_")
        if self.value == self.stop:
            raise StopIteration
        self.value += 1
        return self.value ** 2


class Squares2:
    """
    多(个活跃的)迭代器的实现
    """

    def __init__(self, start, stop):
        self.start = start
        self.value = start - 1
        self.stop = stop
        print("init: ", start, stop)

    def __iter__(self):
        """
        重写该方法,让自己成为:iterable
        :return:
        """
        print("__iter__ -- ")
        return Squares2(self.value + 1, self.stop)

    def __next__(self):
        """
        重写该方法,让自己成为:iterator
        :return:
        """
        print("__next__")
        if self.value == self.stop:
            raise StopIteration
        self.value += 1
        return self.value ** 2


if __name__ == '__main__':
    s1 = Squares(1, 4)
    # 一次遍历仅调用一次 __iter__ 方法
    print([x for x in s1])  
    # 一次遍历中,每返回一个值,都会调用一次__next__方法
    print("\n-------------\n")
    s2 = Squares2(1, 4)
    print([x for x in s2])
    print([x for x in s2])

输出如下:

iterttt.py

s1 init ----  1 4
s1: _iter_
s1: _next_
s1: _next_
s1: _next_
s1: _next_
s1: _next_
[1, 4, 9, 16]
s1: _iter_
s1: _next_
[]

-------------

init:  1 4
__iter__ -- 
init:  1 4
__next__
__next__
__next__
__next__
__next__
[1, 4, 9, 16]
__iter__ -- 
init:  1 4
__next__
__next__
__next__
__next__
__next__
[1, 4, 9, 16]

Process finished with exit code 0

感谢:http://blog.csdn.net/raylee2007/article/details/48325653
感谢:http://blog.csdn.net/passionkk/article/details/49929887
感谢:《Learning Python》