object aware of others
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:
_instances = set()
self.myname = 'IamA'
print('This is A')
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().
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list