1. 判断迭代
# coding=utf-8
"""
1.判断xxxx_obj是否可以迭代
2.在第一步成立的前提下,调用iter函数得到xxx_obj对象的__iter__方法的返回值
3.__iter__方法的返回值是一个迭代器
"""
from collections.abc import Iterable
from collections.abc import Iterator
import time
class Classmate(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
return ClassIterator(self)
class ClassIterator(object):
def __init__(self, obj):
self.obj = obj
self.current_num = 0
def __iter__(self):
pass
def __next__(self):
if self.current_num < len(self.obj.names):
ret = self.obj.names[self.current_num]
self.current_num += 1
return ret
else:
raise StopIteration
classmate = Classmate()
classmate.add("laowang")
classmate.add("laoli")
classmate.add("laosan")
# print("是否可迭代:", isinstance(classmate, Iterable))
#
# classmate_iterator = iter(classmate)
# print("是否迭代器:", isinstance(classmate_iterator, Iterable))
# print(next(classmate_iterator))
for name in classmate:
print(name)
time.sleep(1)
2. 简化
# coding=utf-8
"""
1.判断xxxx_obj是否可以迭代
2.在第一步成立的前提下,调用iter函数得到xxx_obj对象的__iter__方法的返回值
3.__iter__方法的返回值是一个迭代器
"""
from collections.abc import Iterable
from collections.abc import Iterator
import time
class Classmate(object):
def __init__(self):
self.names = list()
self.current_num = 0
def add(self, name):
self.names.append(name)
def __iter__(self):
return self
def __next__(self):
if self.current_num < len(self.names):
ret = self.names[self.current_num]
self.current_num += 1
return ret
else:
raise StopIteration
classmate = Classmate()
classmate.add("laowang")
classmate.add("laoli")
classmate.add("laosan")
classmate.add("李四")
classmate.add("张流森")
# print("是否可迭代:", isinstance(classmate, Iterable))
#
# classmate_iterator = iter(classmate)
# print("是否迭代器:", isinstance(classmate_iterator, Iterable))
# print(next(classmate_iterator))
for name in classmate:
print(name)
time.sleep(1)
3. Fibonacci数列
# coding=utf-8
import time
class Fibonacci(object):
def __init__(self, num):
self.current = 0
self.num = num
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
if self.current < self.num:
ret = self.a
self.a, self.b = self.b, self.a+self.b
self.current += 1
return ret
else:
raise StopIteration
fib = Fibonacci(88)
for i, n in enumerate(fib):
print(i, n)
time.sleep(1)
网友评论