List of Objects

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Apr 19 23:22:48 EDT 2007


On Thu, 19 Apr 2007 19:58:35 -0700, datamonkey.ryan wrote:

> Howdy, a (possibly) quick question for anyone willing to listen.
> I have a question regarding lists and Classes; I have a class called
> "gazelle" with several attributes (color, position, etc.) and I need
> to create a herd of them. I want to simulate motion of individual
> gazelles, but I don't want to have to go through and manually update
> the position for every gazelle (there could be upwards of 50). I was
> planning to create an array of these gazelle classes, and I was going
> to iterate through it to adjust the position of each gazelle. That's
> how I'd do it in C, anyway. However, Python doesn't support pointers
> and I'm not quite sure how to go about this. Any help you can provide
> would be greatly appreciated.

First method: create 1000 different gazelles:

list_of_beasties = []
for i in xrange(1000): # create 1000 beasties
    args = (i, "foo", "bar") # or whatever
    list_of_beasties.append(Gazelle(args))


Second method: create 1000 different gazelles by a slightly different
method:

list_of_beasties = [Gazelle((i, "foo", "bar")) for i in xrange(1000)]

Third method: create 1000 copies of a single gazelle:

list_of_beasties = [Gazelle(args)] * 1000
# probably not useful...

Forth method: create identical gazelles, then modify them:

list_of_beasties = [Gazelle(defaults) for i in xrange(1000)]
for i, beastie in enumerate(xrange(1000)):
    list_of_beasties[i] = modify(beastie)



-- 
Steven D'Aprano 




More information about the Python-list mailing list