Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Creating an iterator in a class

Reply
Thread Tools

Re: Creating an iterator in a class

 
 
Peter Otten
Guest
Posts: n/a
 
      12-27-2012
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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
RE: Creating an iterator in a class Joseph L. Casale Python 0 12-27-2012 07:58 PM
Re: Creating an iterator in a class Ian Kelly Python 0 12-27-2012 06:35 PM
RE: Creating an iterator in a class Joseph L. Casale Python 0 12-27-2012 03:45 PM
Creating an iterator in a class Joseph L. Casale Python 1 12-27-2012 03:34 PM
Difference between Java iterator and iterator in Gang of Four Hendrik Maryns Java 18 12-22-2005 05:14 AM



Advertisments