[Tutor] class Clowning: saving references to other instances

alan.gauld@bt.com alan.gauld@bt.com
Mon, 17 Dec 2001 15:46:22 -0000


>     self.location = location    # an integer, unique
>     self.index = index          # also unique integer
>     self.name = uppercase[index]  # uppercase letter, also 

Huh? index is a unique integer... but you are taking 
the uppercase of it?

> from one Clown instance to another. The 
> distance(self, other) method uses "exec" 
> to store the distance values in self.(other.name) 

Oh dear, not again... ;-)
Using exec for this is really not very good.
A dictionary to store these would be better.

self.others = {}
self.others[other.name] = dist

and 

other.others[self.name] = dist

> Because it's tied to the way I'm storing these 
> instances, I don't like the way it works 

Correct, if you want to access things by a string key 
(name in this case) the best solution is nearly 
always to use a dictionary and nearly never to use 
exec()!

> how the data is stored I'll also have to change 
> the class method.

Not by much.

> The reason why I'm doing this is just to save 
> a little redundant processing. 

But you are introducing a heap of redundant 
processing by calling exec!

> One solution would be to put the "exec" code in a function 

That tidies it up a little but doesn't really help.

> should maintain them all in a single self.distances list:
>     [(B, 5.0), (C, 1.414), (D, 7.6645), ...]

Or a DICTIONARY? 

{ "B":5.0, "C":1.414,....}


> Then the distance(self, other) method filters self.distances 
> "x[0] == str(other)". If found, return x[1], 

  if x.has_key(str(other)) : return x[str(other)]
  else: return # call distance(...) 


>     self.distances.append((other.name, distance))
>     other.distances.append((self.name, distance))

Looks a lot better, and more OO like.

> Have I figured out my own solution?!? :) 

Getting closer, but dictionaries instead of lists 
would make it all much easier IMHO.

> [1] from an old Jim Croce song, "Operator", appx. 1971 (?)

Yeah, Nice taste in music :-)

Alan g.