Python: How to pass more than one argument to the property getter?

前端 未结 7 1971
清酒与你
清酒与你 2021-01-31 06:48

Consider the following example:

class A:
    @property
    def x(self): return 5

So, of course calling the a = A(); a.x will retur

7条回答
  •  执笔经年
    2021-01-31 07:31

    I just ran into this issue. I have class Polynomial() and I'm defining a gradient that I would like to return a function if no arguments or evaluate if there are arguments. I want to store the gradient as an attribute so I don't need to calculate it every time I need to use it, and I want to use @property so the gradient attribute is calculated lazily. My solution was to define a class Gradient with a defined call method for Polynomial's grad property to return.

    @property
    def grad(self):
        """
        returns gradient vector
        """
        class Gradient(list):
            def __call__(self, *args, **kwargs):
                res = []
                for partial_derivative in g:
                    res.append(partial_derivative(*args, **kwargs))
                return res
        g = Gradient()
        for i in range(1, len(self.term_matrix[0])):
            g.append(self.derivative(self.term_matrix[0][i]))
        return g
    

    And then I have the following tests pass successfully:

    def test_gradient(self):
        f = Polynomial('x^2y + y^3 + xy^3')
        self.assertEqual(f.grad, [Polynomial('2xy + y^3'), Polynomial('x^2 + 3xy^2 + 3y^2')])
        self.assertEqual(f.grad(x=1, y=2), [12, 25])
        f = Polynomial('x^2')
        self.assertEqual(f.grad(1), [2])
    

    So, for this issue we could try:

    class A:
        @property
        def x(self):
            class ReturnClass(int):
                def __call__(self, neg=False):
                    if not neg:
                        return 5
                    return -5
            return ReturnClass()
    

提交回复
热议问题