finding name of instances created
Steven Bethard
steven.bethard at gmail.com
Fri Jan 21 21:21:57 EST 2005
André wrote:
> 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()
It looks like you want PrivateClass.dict updated every time that
globals() is updated. You can just use globals directly instead:
py> class PrivateClass(object):
... def __init__(self, globals):
... self.globals = globals
... def apparently_simple_method(self):
... for name, value in self.globals.iteritems():
... if value is self:
... print "instance %s called not so simple" % name
...
py> def public_class():
... return PrivateClass(globals())
...
py> alpha = public_class()
py> alpha.apparently_simple_method()
instance alpha called not so simple
py> beta = public_class()
py> beta.apparently_simple_method()
instance beta called not so simple
On the other hand, the iteration in
PrivateClass.apparently_simple_method has a very bad code smell...
Steve
More information about the Python-list
mailing list