problem using array of instances
Don Arnold
dlarnold at west.com
Tue Feb 11 15:19:16 EST 2003
Anton Muhin <antonmuhin at sendmail.ru> wrote in message news:<b2afis$1neh$1 at news.peterlink.ru>...
> zenguyuno at yahoo.com wrote:
> > I'm stuck on this one:
> >
> > I defined a class, call it boat.
> >
> > I created a list of instances, call it pop, so pop[i] is an instance of
> > the boat class, and I made pop[0], pop[1], etc., all boats.
> >
> > The boat class has a method defined, call it go().
> >
> > I want to define a function and pass i to it. Then inside the function
> > I want it to call the go() method of the ith boat, like pop[i].next.
> > This didn't work; Python thinks that pop[i] is an int, and doesn't have
> > a go() method.
> >
> > I tried passing pop[i] to the function, so it would know that pop[i] was
> > a boat, but that didn't work either. (same error)
> >
> > pop, the list of boats, is global. I put a global statement in the
> > function.
> >
> > I'm using Python 2.2 with Windows 98.
> >
> > Thanks
> >
> > z
> It's almost impossible to understand what is going on. Please, post some
> actual code.
>
> Anton.
seems straightforward to me:
pop = []
class boat:
def __init__(self, i):
self.id = i
def go(self):
print 'boat #', self.id, 'is going.'
def launch(i):
global pop
pop[i].go()
for i in range(10):
pop.append(boat(i))
for i in range(9,-1,-1):
launch(i)
[--- output ---]
>>>
boat # 9 is going.
boat # 8 is going.
boat # 7 is going.
boat # 6 is going.
boat # 5 is going.
boat # 4 is going.
boat # 3 is going.
boat # 2 is going.
boat # 1 is going.
boat # 0 is going.
HTH,
Don
More information about the Python-list
mailing list