Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Creating an iterator in a class (http://www.velocityreviews.com/forums/t955862-re-creating-an-iterator-in-a-class.html)

Peter Otten 12-27-2012 03:14 PM

Re: Creating an iterator in a class
 
Joseph L. Casale wrote:

> I am writing a class to provide a db backed configuration for an
> application.
>
> In my programs code, I import the class and pass the ODBC params to the
> class for its __init__ to instantiate a connection.
>
> I would like to create a function to generically access a table and
> provide an iterator. How does one create a function in a class that takes
> an argument and returns an iterator? I saw some examples where the class
> gets instantiated with the table defined but I was hoping not to do this
> so I could continue to access various tables through one
> connection/cursor.


Have the method yield instead of returning:

>>> class Names:

.... def __init__(self, template):
.... self.template = template
.... def generate_names(self, upto):
.... for index in range(1, upto+1):
.... yield self.template.format(index)
....
>>> names = Names("file{}.txt")
>>> for name in names.generate_names(3):

.... print name
....
file1.txt
file2.txt
file3.txt
>>> list(names.generate_names(2))

['file1.txt', 'file2.txt']
>>> g = names.generate_names(3)
>>> next(g)

'file1.txt'
>>> next(g)

'file2.txt'
>>> next(g)

'file3.txt'
>>> next(g)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration




All times are GMT. The time now is 09:57 AM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


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