Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python 迭代器代码示例
class A():
def __init__(self):
self.v = [1,2,3,4,5,6]
self.step = 0
def __iter__(self):
return self
def next(self):
if self.step >= len(self.v):
raise StopIteration
v = self.v[self.step]
self.step += 1
return v
class ReverseIter(object):
def __init__(self, l):
self.l = l
self.step = len(self.l)-1
def __iter__(self):
return self
def next(self):
if self.step < 0:
raise StopIteration
v = self.l[self.step]
self.step -= 1
return v
class zrange:
def __init__(self, n):
self.n = n
def __iter__(self):
return zrange_iter(self.n)
class zrange_iter:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
# Iterators are iterables too.
# Adding this functions to make them so.
return self
def next(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
def main2():
for i in ReverseIter([1,2,3,4]):
print i
def main1():
a = A()
for i in a:
print i
def main3():
z = zrange(5)
print list(z)
print list(z)
if __name__ == '__main__':
main1()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.