Skip to content

Commit e21a558

Browse files
committed
Add generator object demonstration
1 parent dd0da44 commit e21a558

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

GeneratorObject/src/generatorobj.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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('\nNote: 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()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy