finding name of instances created

Steven Bethard steven.bethard at gmail.com
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
> 
>>>a.apparently_simple_method()
> 
> and that, behind the scene, I could translate that as
> 
>>>my_dict['a'].not_so_simple_method()
> 
> 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>

Steve



More information about the Python-list mailing list