object aware of others

Jerry Hill malaclypse2 at gmail.com
Sun Jan 29 12:45:47 EST 2012


On Sun, Jan 29, 2012 at 1:47 AM, Lee <lchaplin13 at gmail.com> wrote:

> I was afraid that a list/set/dictionary and alike is the answer, but,
> anyway, thanks everybody.
>
>
It doesn't seem too bad to keep track of the instances in the class object
using weak references (http://docs.python.org/py3k/library/weakref.html).
Here's an example that seems to do what you're asking using python 3.2, but
it should be pretty similar in python 2:

import weakref

class A:
    _instances = set()
    def __init__(self):
        self.myname = 'IamA'
        print('This is A')
        self.__class__._instances.add(weakref.ref(self))
    def foo(self):
        print("foo")
    def update(self):
        for ref in self.__class__._instances:
            obj = ref()
            if obj is not None:
                print("The only friends I've got are ", ref, obj.myname)


If you're creating lots of instances of A and deleting them, it would
probably be worth removing the old weakrefs from the _instances set instead
of just ignoring them when calling update().

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120129/ba233281/attachment-0001.html>


More information about the Python-list mailing list