为什么这个简单的代码行不起作用,即使它应该基于输出?
Why does this simple code line not work even though it should based on the output?
当函数 square(x) 得到一个 var 时,它 returns var*var。当函数没有得到 var 时,它 returns 一个所有使用过的 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 值,但没有将它们相乘。
您还需要 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])
当函数 square(x) 得到一个 var 时,它 returns var*var。当函数没有得到 var 时,它 returns 一个所有使用过的 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 值,但没有将它们相乘。
您还需要 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])