0

装飾段階で変数を追加するPythonでデコレータを構築しようとしています。別の関数の結果に対して関数を実行するだけのデコレータの記述方法は知っていますが、変数を追加する構文に問題があります。基本的に、私はこのドット積関数を使用したいと思います。

def dot(x,y):
    temp1=[]
    for i in range(len(x)):
        temp1.append(float(x[i])*y[i])
    tempdot=sum(temp1)
    return tempdot 

そして、結果から値'b'を減算します。これらはすべて、パラメーターx、y、bが指定された1つの大きな関数に含まれます。

この場合、装飾機能を悪用しようとしていますか?ありがとう。

4

1 に答える 1

2
import functools

def subtracter(b):
    def wrapped(func):
        @functools.wraps(func)
        def decorated_func(*args, **kwargs):
            return func(*args, **kwargs) - b
        return decorated_func
    return wrapped

次に、それをとして使用します

@subtracter(b=5)
def dot(x,y):
    temp1=[]
    for i in range(len(x)):
        temp1.append(float(x[i])*y[i])
    tempdot=sum(temp1)
    return tempdot

ちなみに、ドット関数は次のようなジェネレータ式で短縮できます。

def dot(x, y):
    return sum(float(x)*y for x, y in zip(x, y))
于 2012-12-06T15:51:20.173 に答える