On Sun, Jan 29, 2012 at 1:47 AM, Lee <lchapli...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to