为什么这个简单的代码行即使它应该基于输出也不起作用?

时间:2021-01-12 14:06:44

标签: python output python-decorators

当函数 square(x) 得到一个 var 时,它返回 var*var。当函数没有得到 var 时,它会返回一个包含所有使用过的 var 的列表。

def square_or_list(func):
    def wrapper(*arg):
        if not arg:
            return last
        else:
            last.append(arg[0])
            func(arg[0])

    last = []
    return wrapper

@square_or_list
def square(x):
    print(x)
    return x**2

print(square(3))
print(square(4))
print(square())

这是输出:

3
None
4
None
[3, 4]

如您所见,程序打印了正确的 x 值,但不会将它们相乘。

1 个答案:

答案 0 :(得分:1)

您还需要在 return 块中else

 def wrapper(*arg):
    if not arg:
        return last
    else:
        last.append(arg[0])
        # you need to return for the for a correct recursive call
        return func(arg[0])