finding name of instances created

André andre.roberge at gmail.com
Fri Jan 21 20:57:48 EST 2005


Using the method suggested by Steven Bethard, I *almost* got it working
the way I would like.
Here's my program:
===
.class PrivateClass(object):
.    dict = {}
.    def not_so_simple_method(self):
.        for name in PrivateClass.dict.keys():
.            if PrivateClass.dict[name] == self:
.                print "instance " + name + " called not so simple"
.    apparently_simple_method = not_so_simple_method

.    def __init__(self):
.        print "instance created"
.        for name, value in globals().iteritems():
.            if isinstance(value, PrivateClass):
.                PrivateClass.dict[name] = value

.def public_class():
.    return PrivateClass()

.print "=== start==="
.alpha = public_class()
.print "created alpha"
.print PrivateClass.dict
.print "### alpha is not there\n"

.beta = public_class()
.print "created beta"
.print PrivateClass.dict
.print "### we are always one behind in the dict content\n"

.alpha.apparently_simple_method()
.beta.apparently_simple_method()
=================================
The output follows:
=== start===
instance created
created alpha
{}
### alpha is not there

instance created
created beta
{'alpha': <__main__.PrivateClass object at 0x0117CDD0>}
### we are always one behind in the dict content

instance alpha called not so simple
=======
Note that instance beta was never recognized when it called "apparently
simple method".

I'm sure there must be a way to do this....

André




More information about the Python-list mailing list