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>]
If that's all your descriptor do, it's a bit of an abuse of the descriptor protocol. Just overriding your class
__new__
or__init__
would be simpler: