faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Self-registering objects

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 262, Gordon McMillan


"""
Packages: oop
"""
""" 
> 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 ####> }
>
> [...]
> 
"""
__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
>>>
(BTW: you don't need global on __register__, because you are 
not changing the binding, you are mutating the object).
"""