5

私の考えは、合計/減算/...一緒にできる特定の関数オブジェクトを作成し、同じプロパティを持つ新しい関数オブジェクトを返すことです。このコード例は、うまくいけば、アイデアを示しています。

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 をサブクラス化し、callable をコンストラクターに渡さずにcall method__ をカスタマイズする必要があるとします。私は例を挙げなければなりません(実際、これは私が最初にこの質問を投稿したコードです)。

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)

この場合、さらに作業が必要です。

4

2 に答える 2

2

ここには存在する必要のないコードがたくさんあり、必要以上に複雑です。

たとえば、__class__アトリビュートはいわゆる「マジック」アトリビュートの 1 つです。マジック属性は特別で、メタプログラミングを使用している場合など、特別な場合にのみ使用する必要があります。ここではコードでクラスを作成する必要はありません。

もう 1 つの例は、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))

これは、このような問題を解決する従来の方法ではないことに注意してください。伝統的に、ラムダを避け、ここで式ツリーを使用します。式ツリーを使用する利点は、結果の式を代数的に操作できることです。たとえば、それらを解いたり、正確な導関数を計算したり、方程式として出力したりできます。

于 2012-05-31T23:09:48.797 に答える
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直接呼び出すことができます。

于 2012-05-31T23:13:18.087 に答える