How do I get a reference to all classes implementing descriptor object in python

Viewed 352

I am creating a descriptor, and I want to create a list inside it that holds references to all objects implementing it, it is supposed to be some kind of a shortcut where I can call the method on the next instance in line from the instances.

The only daft solution I could find is just on __init__ of each objects trigger the setter on descriptor that adds the item to the list, even though that solution does work indeed, I can sense that something is wrong with it.

Does anyone have a better way of adding the class instance to a descriptor list other than setting arbitrary value on __init__, just to trigger the 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>]
1 Answers
Related