def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
@smart_divide
def divide(a,b):
return a/b
print(divide(10,2)) # prints 5, correct
代码段2:
def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a,b)
return inner
def divide(a,b):
return a/b
print(smart_divide(divide(10,2))) # why is this printing function address ?
第二个片段是错误的。
@smart_divide
def divide(a,b):
...
divide(10,2)
相当于
smart_divide(divide)(10, 2)
# Not to smart_divide(divide(10,2))
看到区别了吗?smart_divide
需要一个函数。你给它提供了一个浮子。如果你尝试再次调用它,你会得到预期的错误'float' object is not callable
:
smart_divide(divide(10, 2))(10, 2)
TypeError: 'float' object is not callable