Python中的自适应描述符

时间:2015-09-28 00:47:57

标签: python python-3.x numpy python-descriptors

我想在返回代理对象的类上创建某种描述符。索引时,代理对象检索对象的成员并将索引应用于它们。然后它返回总和。

如,

class NDArrayProxy:

    def __array__(self, dtype=None):
        retval = self[:]
        if dtype is not None:
            return retval.astype(dtype, copy=False)
        return retval


class ArraySumProxy(NDArrayProxy):

    def __init__(self, arrays):
        self.arrays = arrays

    @property
    def shape(self):
        return self.arrays[0].shape

    def __getitem__(self, indices):
        return np.sum([a[indices]
                       for a in self.arrays],
                      axis=0)

当我将实际数组作为成员变量时,此解决方案工作正常:

class CompartmentCluster(Cluster):

    """
    Base class for cluster that manages evidence.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.variable_evidence = ArraySumProxy([])

class BasicEvidenceTargetCluster(CompartmentCluster):

    # This class variable creates a Python object named basic_in on the
    # class, which implements the descriptor protocol.

    def __init__(self,
                 *,
                 **kwargs):
        super().__init__(**kwargs)

        self.basic_in = np.zeros(self.size)
        self.variable_evidence.arrays.append(self.basic_in)

class ExplanationTargetCluster(CompartmentCluster):

    """
    These clusters accept explanation evidence.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.explanation_in = np.zeros(self.size)
        self.variable_evidence.arrays.append(self.explanation_in)

class X(BasicEvidenceTargetCluster, ExplanationTargetCluster):
    pass

现在我已经将我的数组更改为Python描述符(cluster_signal实现描述符协议返回一个numpy数组):

class CompartmentCluster(Cluster):

    """
    Base class for cluster that manages evidence.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.variable_evidence = ArraySumProxy([])

class BasicEvidenceTargetCluster(CompartmentCluster):

    # This class variable creates a Python object named basic_in on the
    # class, which implements the descriptor protocol.

    basic_in = cluster_signal(text="Basic (in)",
                              color='bright orange')

    def __init__(self,
                 *,
                 **kwargs):
        super().__init__(**kwargs)

        self.variable_evidence.arrays.append(self.basic_in)

class ExplanationTargetCluster(CompartmentCluster):

    """
    These clusters accept explanation evidence.
    """

    explanation_in = cluster_signal(text="Explanation (in)",
                                    color='bright yellow')

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.variable_evidence.arrays.append(self.explanation_in)

class X(BasicEvidenceTargetCluster, ExplanationTargetCluster):
    pass

这不起作用,因为append语句附加了描述符调用的结果。我需要的是附加绑定方法或类似代理。修改我的解决方案最好的方法是什么?简而言之:变量basic_inexplanation_innumpy数组。他们现在是描述符。我想开发一些版本的ArraySumProxy,它与描述符一起使用,而不是需要实际的数组。

1 个答案:

答案 0 :(得分:1)

当您访问描述符时,它将被评估,您只能获得该值。由于你的描述符并不总是返回相同的对象(我猜你不能使它成为avioid?),你不想在初始化代理时访问描述符。

避免访问它的最简单方法是记住它的名字,而不是:

self.variable_evidence.arrays.append(self.basic_in)
你这样做:

self.variable_evidence.arrays.append((self, 'basic_in'))

然后,当然,variable_evidence必须注意这一点并{{​​1}}进行访问。

另一种选择是使描述符返回一个稍后要求的代理对象。我不知道你在做什么,但这可能是太多代理人的好品味......

修改

或者......你可以存储吸气剂:

getattr(obj, name)