0

I am currently learning about decorators, this example is supposed to be a basic decorator that saves the result of a recursive fibonacci function, but there are several questions I have. first of all "fn", is that just the name of a variable? or is it a part of the python language. Same question for 'KeyError'. I also don't understand why in the body of the function, args sometimes has a * in front and other times doesn't (shouldn't it always have a *)

def memoize(fn):
    stored_results = {}

    def memoized(*args):
        try:
            return stored_results[args]
        except KeyError:
            result = stored_results[args]=fn(*args)
            return result
return memoized

def fibonacci(n):
    if n == 0 or n == 1:
        return n
    else:
        return (fibonacci(n-1)+fibonacci(n-2))


@memoize
fibonacci(5)
4

1 に答える 1

0
  1. 正しくインデントします。

    def memoize(fn):
        stored_results = {}
    
        def memoized(*args):
            try:
                return stored_results[args]
            except KeyError:
                result = stored_results[args]=fn(*args)
                return result
        return memoized
    #^^^
    
  2. @memoize行の前にある必要がありますdef ...

    @memoize # <-- should be here
    def fibonacci(n):
        if n == 0 or n == 1:
            return n
        else:
            return (fibonacci(n-1)+fibonacci(n-2))
    
  3. fibonacciせずに電話するだけ@memoize

    fibonacci(5)
    

まず「fn」ですが、それは単なる変数の名前ですか?

関数オブジェクト。では、fibonacci関数です。

「KeyError」に対する同じ質問

引数に対して以前にメモ化された値がない場合は、stored_results[args]が発生しKeyErrorます。(TypeErrorハッシュ化できない値を引数として渡す場合)。

また、関数の本体で args の前に * がある理由もわかりません

memoize複数の引数を取ることができる別の関数でデコレータを動作させるため。

于 2013-10-19T05:21:22.043 に答える