[Tutor] self knowledge

Kent Johnson kent37 at tds.net
Fri Oct 21 20:44:48 CEST 2005


Ethan Ligon wrote:
> 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')

Why does this matter? Why do you need the name both places?

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

The only ways to do this are awkward and kludgy - you have to inspect the stack and find out the name of the variable in the caller. Don't do it.

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

I think this is the third time this question has come up this week! Usually the answer is to put your data in a dictionary or list. Here is another version:
http://mail.python.org/pipermail/tutor/2005-October/042371.html




More information about the Tutor mailing list