self-registering objects?
Gordon McMillan
gmcm at hypernet.com
Fri Oct 29 16:57:49 EDT 1999
Ionel Simionescu writes:
>
> I would like objects of a certain class to be able of registering
> themselves in a global dictionary, __register__, possibly upon
> __init__.
>
> __register__ should contain associatins such as:
>
> { 'ID': <__main__.certain_class instance at ####> }
>
> Unfortunately, the naive:
>
> def __init__(self, etc.):
> global __register__
> self.ID = 'instance1'
> __register__[self.ID] = self
>
> Does NOT work.
>
> The object that I find in the __register__ under the given ID is
> apparently just the bare bones of the class and gets none of the
> changes incured to the instance after registration.
>
> It's is not a problem if I register the object "from outside",
> but I would like to understand what's going on...
So would I!
--------------------------------------------
__register__ = {}
class A:
def __init__(self, arg):
__register__[id(self)] = self
self.arg = arg
a1 = A(1)
a2 = A(2)
for a in __register__.values():
print `a`, a.arg
------------------------------------------------------
When run, outputs:
<__main__.A instance at 7fb880> 2
<__main__.A instance at 7fb7f0> 1
>>>
In fact, __init__ is run after the instance construction is
complete, so whatever is going wrong is _not_ what you think
is going wrong!
(BTW: you don't need global on __register__, because you are
not changing the binding, you are mutating the object).
- Gordon
More information about the Python-list
mailing list