python Class: 面向对象高级编程 __iter__ 和 next()
2018-07-20 10:41
465 查看
官网解释:New in version 2.2.
Return the iterator object itself. This is required to allow both containers and iterators to be used with the
Return the next item from the container. If there are no further items, raise the
也就是说 __iter__与next()是配套使用的。
Fibonacci数列:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fibo(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 10000:
raise StopIteration()
return self.a, self.b
for n in Fibo():
print n
运行失败:
怎么用class做才能成功呢?????后来,才发现,我2.7版本的解释器不支持,用网页上的Python3在线编程解释器完美运行。。。。。。is ri le gou le.附使用的python3环境:http://www.dooccn.com/python3/
请问各位大佬,在2.7版本中我该怎么使用 __iter__ 呢??求教!!!
iterator.
__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the
forand
instatements. This method corresponds to the
tp_iterslot of the type structure for Python objects in the Python/C API.
iterator.
next()
Return the next item from the container. If there are no further items, raise the
StopIterationexception. This method corresponds to the
tp_iternextslot of the type structure for Python objects in the Python/C API.
也就是说 __iter__与next()是配套使用的。
Fibonacci数列:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fibo(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 10000:
raise StopIteration()
return self.a, self.b
for n in Fibo():
print n
运行失败:
怎么用class做才能成功呢?????后来,才发现,我2.7版本的解释器不支持,用网页上的Python3在线编程解释器完美运行。。。。。。is ri le gou le.附使用的python3环境:http://www.dooccn.com/python3/
请问各位大佬,在2.7版本中我该怎么使用 __iter__ 呢??求教!!!
相关文章推荐
- python Class:面向对象高级编程 __call__& callable()
- python Class:面向对象高级编程 __str__ / __repr__
- python Class:面向对象高级编程 @property
- python Class:面向对象高级编程 Enum(枚举)、@unique
- python Class:面向对象高级编程
- python Class:面向对象高级编程 元类:type
- python Class:面向对象高级编程 元类:metaclass
- python Class:面向对象高级编程 __getitem__
- python Class:面向对象高级编程 @property
- python Class:面向对象高级编程 __getattr__
- Python 面向对象高级编程――定制类
- 廖雪峰Python教程1轮还没学明白的(3) -- 面向对象高级编程 -- 定制类 -- __getattr__之链式调用
- python2.7学习笔记(10) ——面向对象高级编程
- 《每日一课》Python入门之面向对象高级编程
- 【Python】学习笔记——-8.5、面向对象高级编程:5.使用枚举类
- Python面向对象高级编程
- Python3 基础:面向对象高级编程(上)
- python 2.7 : 面向对象高级编程
- Python 面向对象高级编程――使用枚举和元类
- python学习(13)——面向对象高级编程