How do I get a reference to all classes implementi

2020-04-07 23:05发布

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条回答
够拽才男人
2楼-- · 2020-04-07 23:31

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:

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
查看更多
登录 后发表回答