以编程方式在Python中创建算术特殊方法(又名工厂函数HOWTO)

时间:2012-05-31 22:31:22

标签: python class factory

我的想法是创建可以加总/减去/ ...的特定函数对象,返回具有相同属性的新函数对象。希望这个示例代码能够证明这个想法:

from FuncObj import Func

# create some functions
quad = Func(lambda x: x**2)
cube = Func(lambda x: x**3)

# now combine functions as you like
plus = quad + cube
minus = quad - cube
other = quad * quad / cube

# and these can be called
plus(1) + minus(32) * other(5)

我编写了以下代码,希望对其进行评论和记录,以解释我想要实现的目标。

import operator

class GenericFunction(object):
    """ Base class providing arithmetic special methods. 
        Use derived class which must implement the 
        __call__ method.
    """

    # this way of defining special methods works well
    def __add__(self, operand):
        """ This is an example of a special method i want to implement. """
        obj = GenericFunction()
        # this is a trick from Alex Martelli at
        # http://stackoverflow.com/questions/1705928/problem-with-making-object-callable-in-python
        # to allow per-instance __call__ methods
        obj.__class__ = type(obj.__class__.__name__, (obj.__class__,), {})
        obj.__class__.__call__ = lambda s, ti: self(ti) + operand(ti)
        return obj

    # on the other hand this factory function seems buggy 
    def _method_factory(operation, name):
        """ Method factory.
        Parameters
        ----------
        op : callable
            an arithmetic operator from the operator module
        name : str
            the name of the special method that will be created
        Returns
        -------
        method : callable
            the __***__ special method
        """
        def method(s, operand):
            obj = GenericFunction()
            obj.__class__ = type(obj.__class__.__name__, (obj.__class__,), {})
            obj.__class__.__call__ = lambda s, ti: operation(s(ti), operand(ti))
            return obj
        return method

    __sub__ = _method_factory(operator.__sub__, '__sub__')
    __mul__ = _method_factory(operator.__mul__, '__mul__')
    __truediv__ = _method_factory(operator.__truediv__, '__div__')


class Func(GenericFunction):
    """ A customizable callable object. 
        Parameters
        ----------
        func : callable
    """
    def __init__(self, func):
        self.func = func

    def __call__(self, *args):
        return self.func(*args)


if __name__ == '__main__':

    # create some functions
    quad = Func(lambda x: x**2)
    cube = Func(lambda x: x**3)

    # now combine functions
    poly_plus = quad + cube
    poly_minus = quad - cube

    # this is the expected behaviour, and it works well
    # since the __add__ method is defined correctly.
    assert quad(1) + cube(1) == poly_plus(1)

    # this, and the others with * and / result in a "maximum recursion depth exceeded"
    assert quad(1) - cube(1) == poly_minus(1)

我想我错过了一些重要的东西,但我看不到它。

编辑

迪特里希回答后,我忘了提一个角落案。假设我想继承GenericInput,我需要自定义调用方法__,而不将可调用的函数传递给构造函数。我必须举例,(实际上这是我最初发布这个问题的代码)。

class NoiseInput(GenericInput):
    def __init__(self, sigma, a, b, t):
        """ A band-pass noisy input. """
        self._noise = lfilter(b, a, np.random.normal(0, 1, len(t)))
        self._noise *= sigma/self._noise.std()
        self._spline = InterpolatedUnivariateSpline(t, self._noise, k=2)

    def __call__(self, ti):
        """ Compute value of the input at a given time. """
        return self._spline(ti)

class SineInput(GenericInput):
    def __init__(self, A, fc):
        self.A = A
        self.fc = fc

    def __call__(self, ti):
        return self.A*np.sin(2*np.pi*ti*self.fc)

在这种情况下还有一些工作要做。

2 个答案:

答案 0 :(得分:2)

这里有很多代码不需要存在,并且它比它需要的更复杂。

例如,__class__属性是所谓的“魔术”属性之一。魔术属性是特殊的,只需要在特殊情况下使用,例如在使用元编程时。这里不需要按代码创建类。

另一个例子是代码中的Func类,它实际上并没有做任何事情。您可以安全地将其替换为:

def Func(x):
    return x

所以你有相反的问题:你没有“遗失”任何东西,你太过分了。

class Func(object):
    def __init__(self, func):
        self._func = func
    def __call__(self, x):
        return self._func(x)
    def __mul__(self, other):
        return Func(lambda x: self(x) * other(x))
    def __add__(self, other):
        return Func(lambda x: self(x) + other(x))
    def __sub__(self, other):
        return Func(lambda x: self(x) - other(x))

请注意,这是 传统的实现此类问题的方法。传统上,一个人避免使用lambdas并在这里使用表达式树。使用表达式树的优点是可以用代数方式处理结果表达式。例如,您可以解决它们,计算精确的导数,或将它们打印为方程式。

答案 1 :(得分:0)

我假设您希望f(x ** 2) + f(x ** 3)返回一个函数x**2 + x**3?你可以试试这个:

class Func:
    def __init__(self, func):
        self._func = func

    def __call__(self, *args):
        return self._func(*args)

    def __add__(self, other):
        def result(*args):
            return self._func(*args) + other(*args)
        return Func(result)
    __radd__ = __add__

    def __mul__(self, other):
        def result(*args):
            return self._func(*args) * other(*args)
        return Func(result)
    __rmul__ = __mul__

    # etc...

对我有用,比你的要简单得多。

编辑:

您甚至可能不会对算术方法中的self._func调用感到烦恼,只需直接调用self即可。