object query assigned variable name?
John O'Hagan
research at johnohagan.com
Mon May 4 00:26:15 EDT 2009
On Sat, 2 May 2009, John O'Hagan wrote:
> On Fri, 1 May 2009, warpcat wrote:
[...]
> > Given an object:
> >
> > class Spam(object):
> > def __init__(self):
> > # stuff....
> >
> > I'd like it to print, when instanced, something like this:
> > >>> s = Spam()
> >
> > I’m assigned to s!
>
> If you just want the names an instance has in a given namespace, you could
> give your class a method like:
>
> class KnowNames(object):
> def get_names(self, namespace):
> id_str = str(hex(id(self))[:-1])
> return [i for i in namespace if id_str in str(namespace[i])]
>
> which will give you a list of names when called on an instance.
And which is a silly way of saying:
class KnowName(object):
def get_names(self, namespace):
return [i for i in namespace if namespace[i] is self]
removing four function calls, an assignment and a slicing operation from a
mere two lines; certainly a personal best for insanely over-wrought code!
Oops. :) ,
John
More information about the Python-list
mailing list