In this case, I see two options:
Garbage collector
import gc for obj in gc.get_objects(): if isinstance(obj, some_class): dome_something(obj)
This has the disadvantage of being very slow when you have many objects, but it works with types that you have no control over.
Use mixin and weakrefs
from collections import defaultdict import weakref class KeepRefs(object): __refs__ = defaultdict(list) def __init__(self): self.__refs__[self.__class__].append(weakref.ref(self)) @classmethod def get_instances(cls): for inst_ref in cls.__refs__[cls]: inst = inst_ref() if inst is not None: yield inst class X(KeepRefs): def __init__(self, name): super(X, self).__init__() self.name = name x = X("x") y = X("y") for r in X.get_instances(): print r.name del y for r in X.get_instances(): print r.name
In this case, all links are obtained as a weak link in the list. If you often create and delete many instances, you must clear the list of weaknesses after iteration, otherwise there will be a lot of toughness.
Another problem in this case is that you must definitely call the base class constructor. You can also override __new__ , but only the __new__ method of the first base class is used to instantiate. It also only works on types that are under your control.
Change The method of printing all the copies in accordance with a specific format remains in the form of an exercise, but basically it is a variation on for -loops.
Torsten Marek Nov 30 '08 at 13:56 2008-11-30 13:56
source share