can I query an instance for its name?

Emile van Sebille emile at fenx.com
Sat Sep 30 13:56:38 EDT 2000


Luc,

There are many ways that this can be kludged, and certainly
no recommended way.  That's probably why no other posts
specifically addressed your question.  It gets muddier
though, as the memory location storing the instance can be
pointed at and known by many different names.  What you may
want is buried in the traceback, and can be extracted.
(Don't go there).  It's probably best to build whatever
trace/name capabilities you're looking for into the __init__
of your classes.

That said, here is one more deficient way to *guess*:


def who(var, lcls, glbls):
    varid = id(var)
    for d in [lcls, glbls]:
        for k in d.keys():
            if id(d[k]) == varid:
                return "%s is an instance of class %s" % (k,
d[k].__class__.__name__)

class test:
    pass

class test1:
    def who(self, lcls):
        return who(self, lcls, globals())

tvar = test()
print who(tvar, locals(), globals())

tvar = test1()
print tvar.who(locals())
avar = tvar
print tvar.who(locals())


Ducking-the-expected-seasoned-reproach-ly y'rs,

--

Emile van Sebille
emile at fenx.com
-------------------


"Luc Lefebvre" <luc at B57-90.python.org> wrote in message
news:mailman.970327546.5142.python-list at python.org...
> Hi Bjorn,
>
> I would like to see:
>
> >>> x.who()
> >>> x is an instance of class foo
>
> --
> Luc Lefebvre
>
> Open Source, a strategic choice
> for mission-critical applications
>
> Key fingerprint = D2E5 5E35 B910 6F4E 0242  EC63 0FD9 96D0
C7F4 784E
> On Fri, 29 Sep 2000, Bjorn Pettersen wrote:
>
> > so if I do:
> >
> >  x = foo()
> >  y = x
> >  y.who()
> >
> > what should it print?
> >
> > -- bjorn
> >
> > Luc Lefebvre wrote:
> > >
> > > Hi,
> > >
> > > <\newbie alert on>
> > >
> > > I have been attempting to get access to instance
names, eg:
> > >
> > > class foo:
> > >         def __init__(self):
> > >                 pass
> > >
> > >         def who(self):
> > >                 print "%s is an instance of class %s"
% (self.????, self.__class__)
> > >
> > > if __name__=="__main__":
> > >         x=foo()
> > >         x.who() # would expect "x is an instance of
class foo"
> > >
> > > Also, is there a way to enquire as to a given classes
children eg: foo.__children__?
> > >
> > > <\newbie alert off>
> > > tia
> > >
> > > --
> > > http://www.python.org/mailman/listinfo/python-list
> >
>
>





More information about the Python-list mailing list