On 23 Dec 2006 14:38:19 -0800, Adam Atlas <[EMAIL PROTECTED]> wrote: > Is it possible for an object, in its __init__ method, to find out if it > is being assigned to a variable, and if so, what that variable's name > is? I can think of some potentially ugly ways of finding out using > sys._getframe, but if possible I'd prefer something less exotic. > (Basically I have a class whose instances, upon being created, need a > 'name' property, and if it's being assigned to a variable immediately, > that variable's name would be the best value of 'name'; to make the > code cleaner and less redundant, it would be best if it knew its own > name upon creation, just like functions and classes do, without the > code having to pass it its own name as a string.)
I guess you mean something like this: >>> olle = Person() >>> olle.name "olle" Instead of: >>> olle = Person("olle") >>> olle.name "olle" It is not possible without ugly hacks. What you could use instead is some kind of registry approach: reg = {} class Person: def __init__(self, name): self.name = name reg[name] = self >>> Person("olle") >>> reg["olle"].name "olle" I think there are thousand different ways you could solve it. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list