finding name of instances created
craig at postnewspapers.com.au
Fri Jan 21 19:29:24 EST 2005
On Fri, 2005-01-21 at 16:13 -0800, André wrote:
> Short version of what I am looking for:
> Given a class "public_class" which is instantiated a few times e.g.
> a = public_class()
> b = public_class()
> c = public_class()
> I would like to find out the name of the instances so that I could
> create a list of them e.g.
> ['a', 'b', 'c']
> I've read the Python Cookbook, Python in a Nutshell, Programming
> Python, Learning Python, ... googled (probably missed something
> obvious), all to no avail.
Yep. The short answer is that the instances don't have names - they're
just bound to names in a particular scope. They can be bound to
different names in the same scope or in other scopes.
You can get a dictionary for a particular scope using locals() then
search it to find the key for a given value. That key will be the name
the object is bound to in that scope.
In general, you won't want to do that - the need to do so probably
suggests a design issue in what you're trying to do.
> If I can do the above, I believe I could do the following thing which
> is what I am really after eventually.
> Given the statement
> >> a = public_class()
> I would like to generate
> >> my_dict['a'] = private_class()
> so that one could write
> >> a.apparently_simple_method()
> and that, behind the scene, I could translate that as
> >> my_dict['a'].not_so_simple_method()
I'm not clear as to why you can't do this as part of the class of which
'a' is an instance.
> as well as do things like
> >> for name in my_dict:
> >> do_stuff(name)
> Any help, pointers, sketches or outline of solution would be greatly
I'm not really able to grasp what you're trying to do (but others
might). It wouldn't hurt if you could post a description of what you're
actually trying to achieve - /why/ you want this - as that can often be
very helpful both in understanding what you're thinking and in
suggesting a suitable approach or alternative.
More information about the Python-list