我试图理解装饰器,并且对下面的代码感到有些困惑:
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) #In understand everything upto this point. How come when the function
#is called here there is no Error as we are still diving 2 by 0?
return inner
@smart_divide
def divide(a,b):
return a/b
print divide(2,0)
由于
答案 0 :(得分:0)
为什么在这里调用函数时没有错误,因为我们仍然在2比0潜水?
如果b
为零,则修饰函数会更早返回:
if b == 0:
print("Whoops! cannot divide")
return
并且从不执行除零。相反,该函数隐式返回None
(如果你问我,这是一个有点奇怪的选择)。