forked from davehunt00/UW_python_class_demo.code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterators.py
More file actions
66 lines (56 loc) · 1.78 KB
/
Copy pathiterators.py
File metadata and controls
66 lines (56 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#! /usr/bin/env python
#
# This is some examples of a interators
# This is an example from Wesley Chun's book, "Core Python Programming, 2nd ed"
# page 578
class AnyIter(object) :
def __init__(self, data, safe=False) :
self.safe=safe
# See http://docs.python.org/2/library/functions.html#iter
self.iter = iter(data)
def __iter__(self) :
return self
def next(self, howmany=1):
"""This method returns a list of howmany objects out of data (which was
passed in when the object was instantited) until the list of ojects is exhausted."""
retval =[]
for each_item in range(howmany) :
try :
retval.append( self.iter.next() )
except StopIteration :
if self.safe :
break
else :
raise
return retval
if __name__ == "__main__" :
d = {"one":1, "two": 2, "three": 3}
print "The attributes of a dictionary object"
print dir(d)
for i in d:
print i,
print
s = "spam"
print "The attributes of a string object"
print dir(s)
for c in s :
print c,
print
print "Run AnyIter with safe set to false and the list is not exchausted"
i = AnyIter(range(10), safe=False )
# i = iter(a)
for j in range(1,5) :
print j,":",i.next()
print "Run AnyIter with safe set to false and the list is exhausted"
# i = iter(a)
try :
i.next(14)
print j,":",i.next()
except StopIteration,e :
print "StopIteration was raised",e
else :
print "StopIteration was *not* raised"
print "Run AnyIter with safe set to True and the list is exhausted"
i = AnyIter(range(10), safe=True)
# i = iter(a)
print i.next(14)