Chinaunix首页 | 论坛 | 博客
  • 博客访问: 444279
  • 博文数量: 97
  • 博客积分: 1552
  • 博客等级: 上尉
  • 技术积分: 1091
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-17 17:05
个人简介

专注于大规模运维场景运维工具解决方案。欢迎有这方面兴趣的朋友跟我联系。

文章分类

全部博文(97)

文章存档

2014年(12)

2013年(25)

2012年(60)

我的朋友

分类: Python/Ruby

2012-07-16 21:33:40

1.类里面的__iter__

点击(此处)折叠或打开

  1. class NodeIterator(object):
  2.     index = 0
  3.     def __init__(self, nodes):
  4.         self.nodes = nodes;
  5.     def next(self):
  6.         if self.index > len(self.nodes):
  7.             raise StopIteration()
  8.         self.index += 1
  9.         return self.nodes[self.index-1]

  10. class Node():
  11.     nodes = []
  12.     def __init__(self):
  13.         nodes = ["a", "b", 1, 2]
  14.         for dataset in nodes:
  15.             self.nodes.append(dataset)

  16.     def __iter__(self):
  17.         return NodeIterator(self.nodes)

  18. o = Node()
  19. for i in o:
  20.     print i
这个方法可以调用一个实现next方法的迭代器类哦。

阅读(591) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~