How can I get the name of an object???

spex66 at spex66 at
Fri Apr 28 11:20:25 EDT 2000

corrected code version if my cancel haven't worked:

In article <slrn8gglsv.ep7.scarblac-spamtrap at>,
  scarblac-rt at wrote:
> spex66 at wrote in comp.lang.python:
> > In article <etd8zy03m44.fsf at>,
> >   Alex <cut_me_out at> wrote:
> > >
> > > An object could be referred to by any number of names:
> > >
> > > dd = zz ()
> > > ee = dd
> > >
> > > Which name for the object do you wish to know?  ee or dd?
> >
> > dd or in other words, the name of the FIRST made instance...
> What would happen in the following cases:
> 1)
>   dd = zz()
>   ee = dd
>   del dd
>   print ee.__name__
> 2)
>   dd = [xx(), yy(), zz()]
>   print dd[2].__name__
> 3)
>   print zz().__name__
> Classes have a name (the one used in their class: statement).
> Instances have no name, period.
OK, I understand this point very well :-) there are enough good examples

> But why would you need it? In most cases where people try to use
I need it to build navigation-code on the fly for "exec" command. Build
on a knitted database API. I have an instance of the navigation-class,
but for the "exec"code I need the name of the *instance*.

Good for me: there is only one instance necessary, but I don't wanted
to hardcode the name, cause an interactive use i sto restricted.

So I have actually a new approach: a "shadow" instance, of the first
navigation instance.

"""arghh, last 45min I implemented the __setattr__, I don't needed in
my example, but I think it's nice to play with
class shadow:
    #BUILD for internal access on the given instance with a reliable
    #ONLY practible if there is ONE instance of a class
    #Needed for internal code-building purposes
    def hide(self, realinstance):
        self.internal = realinstance

    def __getattr__(self, attrName):
        # Get any other interesting attributes from the base class.
        if (attrName <> 'internal'):
            return self.internal.__dict__[attrName]
            if self.__dict__.has_key('internal'):
                return self.__dict__['internal']

    def __setattr__(self, attrName, value):
        if (attrName <> 'internal'):
            setattr(self.internal, attrName, value)
            self.__dict__['internal'] = value

sw = shadow()
shadowName = 'sw'

class navigation:
    def __init__(self): = 'hallo'

so I can write at the prompt:
>>> from shadow import * #IMPORTANT for me
>>> yy = navigation()
>>>  'hallo'
>>>  'hallo'
>>> sw.test = 7
>>> yy.test
>>> 5

and I have my fixed access for the navigation instance over shadowName
>>> exec " = '%s'" % (shadowName, 'hi')
>>> 'hi'

hmm, and it work for all classes with one instance (I hope :))
and a nice excercise for __getattr__ and __setattr__


> like this, dictionaries are a solution.
> --
> Remco Gerlich

Sent via
Before you buy.

More information about the Python-list mailing list