装饰函数执行后从装饰器访问变量值

时间:2020-04-30 18:39:08

标签: python python-3.x python-decorators


def memoize(fn):
    memory=dict()
    def inner(inpt):
        if not inpt in memory:
            memory[inpt] = fn(inpt)
        return memory[inpt]
    return inner

@memoize
def expected_rounds(picks_to_go):
    #algorithm....
    ans += expected_rounds(new_picks_to_go) #some recursion
    #algorithm....
    return ans

函数成功完成执行并返回答案后,如何在memory装饰器中访问(甚至打印)变量memoize

1 个答案:

答案 0 :(得分:0)

我在发布问题后创建的想法使用了类,但是我想继续使用函数装饰器:

function printManyTimes(str) {
    var sentence = str + "is cool"
    for (var i = 0; i < str.length; i += 2) {
        console.log(sentence);
    }
    printManyTimes("Satyam")
}