finding name of instances created

Steven Bethard steven.bethard at
Fri Jan 21 19:46:46 EST 2005

André wrote:
> Given the statement
>>>a = public_class()
> I would like to generate
>>>my_dict['a'] = private_class()
> so that one could write
> and that, behind the scene, I could translate that as
> as well as do things like
>>>for name in my_dict:
>>>    do_stuff(name)

Why can't you just make public_class a factory, alias the method in 
PrivateClass and access the names through locals()?

py> class PrivateClass(object):
...     def not_so_simple_method(self):
...         print "not so simple"
...     apparently_simple_method = not_so_simple_method
py> def public_class():
...     return PrivateClass()
py> a = public_class()
py> a.apparently_simple_method()
not so simple
py> # add 'name' and 'value' to locals() before iteration starts
py> name, value = None, None
py> for name, value in locals().iteritems():
... 	if isinstance(value, PrivateClass):
... 	    print name, value
a <__main__.PrivateClass object at 0x01146D50>


More information about the Python-list mailing list