1
+ '''
2
+ Created on Aug 6, 2017
3
+
4
+ @author: Aditya
5
+
6
+ This program explains the details of generator objects.
7
+ '''
8
+
9
+ class inclusive_range :
10
+ def __init__ (self ,* args ):# this method is constructor
11
+ nargs = len (args )
12
+ if nargs < 1 :raise TypeError ('Requires atleast one argument.' )
13
+ elif nargs == 1 :
14
+ self .stop = args [0 ]
15
+ self .start = 0
16
+ self .step = 1
17
+ elif nargs == 2 :
18
+ self .start ,self .stop = args
19
+ self .step = 1
20
+ elif nargs == 3 :
21
+ self .start ,self .stop ,self .step = args
22
+ else :raise TypeError ('Expected atmost 3 arguments. Got {} arguments.' .format (nargs ))
23
+
24
+ def __iter__ (self ):
25
+ # this method creates the iterator object and we can thus put our generator function over here.
26
+ i = self .start
27
+ while i <= self .stop :
28
+ yield i
29
+ i += self .step
30
+
31
+ def main ():
32
+ o = range (25 )# range object
33
+ print ('Type of range object: ' ,type (o ))
34
+ for i in o :print (i ,end = ' ' )# range object used in context of iterator
35
+ print ('\n Note: range object is a generator.' )
36
+ print ('Also range is exclusive iterator, i.e., it excludes the upper limit.' )
37
+
38
+ print ()
39
+ print ('Illustrating Generator Object in Python.' )
40
+ o = inclusive_range (25 )
41
+ for i in o :print (i ,end = ' ' )
42
+ print ()
43
+
44
+ if __name__ == '__main__' :main ()