How to get a link to all classes implementing a descriptor object in python

I create a descriptor, and I want to create a list in it that contains links to all objects that implement it, it should be a kind of shortcut where I can call the method on the next instance in a row from the instances.

The only stupid solution that I could find, only on __init__each object, was launched by the installer in the descriptor, which adds the item to the list, although this solution really works, I can understand that something is wrong with it.

Does anyone have a better way to add an instance of a class to a descriptor list other than setting an arbitrary value on __init__, just to run setter?

class GetResult(object):
    def __init__(self, value):
        self.instances = []
    def __get__(self, instance, owner):
        return self
    def __set__(self, instance, value):
        self.instances.append(instance)
    def getInstances(self):
        return self.instances




class A(object):
    result = GetResult(0)
    def __init__(self):
        self.result = 0
    def getAll(self):
        print self.result.getInstances()




a1 = A()
a2 = A()
a3 = A()

print a2.result.getInstances()
>> [<__main__.A object at 0x02302DF0>, <__main__.A object at 0x02302E10>, <__main__.Aobject at 0x02302E30>]
+4
1

, . __new__ __init__ :

class Foo(object):
    _instances = []

    def __new__(cls, *args, **kw):
        instance = object.__new__(cls)
        cls._instances.append(instance)
        return instance

    @classmethod
    def get_instances(cls):
        return self._instances
+2

All Articles