sequence of objects
Jeremy Jones
zanesdad at bellsouth.net
Wed Oct 13 11:53:23 EDT 2004
Neal D. Becker wrote:
>What is the recommended way to create a sequence of objects? Assume the
>objects have a default constructor:
>
>class X:
> def __init__(self):
> something
>
>This doesn't work:
>a = 64*(X(),)
>
>This creates a tuple of 64 copies of a single identical object, not 64
>instances of X.
>
>I could create an empty list, then call append (X()) 64 times, but that's
>not very eligant (or maybe efficient). Any suggestions?
>
>
>
The answer is, "it depends on what you are trying to do." Here is _a_
solution:
In [5]: class X:
...: def __init__(self, id):
...: self.id = id
...:
In [6]: def gen_64():
...: for i in range(64):
...: yield X(i)
...:
And if you want to iterate through them, you can do something like:
In [7]: for i in gen_64():
...: print i, i.id
Jeremy Jones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041013/763de7ae/attachment.html>
More information about the Python-list
mailing list