List of Objects

Paddy paddy3118 at
Fri Apr 20 05:18:25 CEST 2007

On Apr 20, 3:58 am, datamonkey.r... at 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.
> Thanks a lot!
> -Ryan

Something like:

import random
class Gazelle(object):
  def __init__(self):
    self.pos = 0, 0

# create a list of instances
gazelles= [ Gazelle() for x in range(5)]

# update gazelle positions
deltaxmin, deltaxmax = -100, +100
deltaymin, deltaymax = -100, +100
for g in gazelles:
  g.pos = (g.pos[0] + random.randint(deltaxmin, deltaxmax),
    g.pos[1] + random.randint(deltaymin, deltaymax) )

The above is untested by the way.

- Paddy.

More information about the Python-list mailing list