problem using array of instances

John Machin sjmachin at lexicon.net
Tue Feb 11 15:40:33 EST 2003


zenguyuno at yahoo.com wrote in message news:<3E488189.207EDB54 at lvcm.com>...
> 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.

'pop' is not a good choice for a name, but that's not causing the
symptoms that you mentioned.

> 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)

Each object carries a pointer to its own type information. There are
no such things as declarations. If pop[i] is an int, then it's an int,
period. This isn't C; you can't do a cast like (boat instance
*)(pop[i]) ...
> 
> pop, the list of boats, is global.  I put a global statement in the
> function.

Presence/absence of "global pop" should make no difference.

As another poster suggested, you should post code; the minimal amount
that demonstrates the problem. In the meantime, here is a minimal code
that follows your description and doesn't have the problem.

pop = []
class boat:
   def go(self):
      print "go:", repr(self)
def the_func(i):
   global pop # irrelevant
   pop[i].go()
if __name__ == "__main__":
   for k in range(5):
      obj = boat()
      print "creation:", k, repr(obj)
      pop.append(obj)
   print repr(pop)
   for k in range(5):
      the_func(k)

You should compare this with your code --- one glaring difference will
be the print statements at instance creation time. You are getting
ints instead of boat instances. Putting in print statements just might
help you find out why.
What are the values of the ints that you are creating? If pop refers
to [0, 1, 2, 3, 4, ....] that should give you a big hint :-)

Below is what I get when I run my code. You should get something
similar; the hex addresses will of course differ.

creation: 0 <__main__.boat instance at 0x007677E8>
creation: 1 <__main__.boat instance at 0x007680D0>
creation: 2 <__main__.boat instance at 0x00767DB0>
creation: 3 <__main__.boat instance at 0x007688A8>
creation: 4 <__main__.boat instance at 0x00769700>
[<__main__.boat instance at 0x007677E8>, <__main__.boat instance at
0x007680D0>, <__main__.boat instance at 0x00767DB0>, <__main__.b
oat instance at 0x007688A8>, <__main__.boat instance at 0x00769700>]
go: <__main__.boat instance at 0x007677E8>
go: <__main__.boat instance at 0x007680D0>
go: <__main__.boat instance at 0x00767DB0>
go: <__main__.boat instance at 0x007688A8>
go: <__main__.boat instance at 0x00769700>

Hope this helps,
John




More information about the Python-list mailing list