PEP: Iterator

Classes can define how they are iterated over by defining an
    __iter__() method; this should take no additional arguments and
    return a valid iterator object.  A class that wants to be an
    iterator should implement two methods: a next() method that behaves
    as described above, and an __iter__() method that returns self.

一个类如果想要有和Iterator一样的行为,需要实现两个基本函数:__iter__()和next(),前者返回类对象self本身,后者返回容器的下一个元素,如果到底最后一个元素,需要抛出异常StopIteration。


下面是关于Dictionary类的相关例子:

This means that we can write

          if k in dict: ...

      which is equivalent to

          if dict.has_key(k): ...
这两个表达式的意义是一样的。

This means that we can write

          for k in dict: ...

      which is equivalent to, but much faster than

          for k in dict.keys(): ...
这两个表达式的意义是一样的。

          for key in dict.iterkeys(): ...

          for value in dict.itervalues(): ...

          for key, value in dict.iteritems(): ...
这三个表达式分别显示的返回了三种Iterator。

你可能感兴趣的:(python)