[Tutor] self knowledge

Ethan Ligon ligon at are.berkeley.edu
Fri Oct 21 20:13:47 CEST 2005


I've devised a simple class; one of the class attributes is an identifier.

Thus,

class Foo:
  def __init__(self,name):
    self.name=name

When using the class in practice, I've found it natural to
create instances of Foo so that the instance itself is called
name.  Thus, I find myself doing things like:

>>> a=Foo('a')
>>> b=Foo('b')

I want the name attribute to depend only on the name of the
original variable; thus

>>> c=a
>>> c.name
'a'

is the desired behavior. 

But this is plainly silly--I'm supplying information on identity
twice when I instantiate each instance---and gives rise to 
two questions. 

First, my immediate inclination is to try and think of 
a way for the object to know its own name (at the time
its instantiated) without being told, perhaps via the 
creation of a name method for Foo.  But the only ways 
I can think of learning this name are all incredibly 
awkward and kludgy.  What's the best way to do this?

Second, because this seems awkward, I strongly suspect 
that there's a pretty fundamental problem with the way
I'm approaching the problem.  When the name of a variable
is itself information which might be useful, what's the
right way convey this information?  

Thanks,
-Ethan
    
-- 
Ethan Ligon, Assoc. Professor                           ligon at are.berkeley.edu
Dept. of Agricultural & Resource Economics
University of California                        http://are.berkeley.edu/~ligon
Berkeley, CA 94720-3310                                          (510)643-5411


More information about the Tutor mailing list