[Tutor] Accessing class instances [Party people]

Alex Newby alex at alexnewby.com
Fri Mar 19 01:08:32 EST 2004


This example is really great! 

I just thought you should know:)

Sincerely,


Alex Newby


Date: Wed, 17 Mar 2004 21:36:48 -0800 (PST)
From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>

Here, we're letting each Person talk to one other by letting them "meet"
each other first.  What's neat is that this approach allows us to tie
these folks together in interesting and wacky ways:

###
>>> def party(people):
...     for p in people: p.greet()
...
>>> c.meet(b)
>>> b.meet(a)
>>> party([a, b, c])
I Alice greet you, Bob
I Alice greet you, Cathy
I Bob greet you, Alice
I Cathy greet you, Bob
###


The key to this is to let each instance keep a little bit of memory of
who
they've met.  In the Person class definition, we say that every Person
remembers by keeping track of their aquaintences in a 'people' list.


But if a person just needs to remember one person, we can just say:

###
>>> class SolitaryPerson:
...     def __init__(self, name):
...         self.name = name
...         self.friend = None
...     def meet(self, other):
...         self.friend = other
...     def greet(self):
...         if self.friend:
...             print "I", self.name, "greet you,", self.friend.name
...         else:
...             print "but I don't have any friends.  Waaa."
...
>>> d = SolitaryPerson("Dan")
>>> d.greet()
But I Dan don't have any friends.  Waaa.
>>> d.meet(a)
>>> d.meet(b)
>>> d.meet(c)
>>> d.meet(d)
>>> d.greet()
I Dan greet you, Dan
###

in which case, we get a SolitaryPerson who is really close-knit.

Anyway, so no lists are really necessary.  But the idea of these
instances
talking to each other, keeping tabs on each other by maintaining some
state in 'self', should be a little clearer.

This approach of getting instances aware of each other is usually
preferred over hardcoding references to other modules --- it's a little
easier to redefine the ties that bind each other with the matchmaking
approach.

Hope this helps!



More information about the Tutor mailing list