object query assigned variable name?
research at johnohagan.com
Sat May 2 00:22:20 EDT 2009
On Fri, 1 May 2009, warpcat wrote:
> I've passed this around some other groups, and I'm being told
> "probably not possible". But I thought I'd try here as well :) I
> *did* search first, and found several similar threads, but they
> quickly tangented into other specifics of the language that were a bit
> over my head :) At any rate, here's a simple example, I'd love to
> know if as shown, is somehow possible:
> 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:
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.
But if you try moving that method inside __init__(), it returns an empty list
because any assignment is not yet in the namespace.
I can see that it's tantalizing, though, because _somebody_ must know about
the assignment; after all, we just executed it!
More information about the Python-list