我试图理解Decorator,并对下面的代码感到有点困惑:
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)谢谢
发布于 2014-12-11 14:59:14
为什么当函数在这里被调用时没有错误,因为我们仍然是2乘0?
如果b为零,则修饰函数将在前面返回:
if b == 0:
print("Whoops! cannot divide")
return而零的除法永远不会被执行。相反,函数隐式返回None (如果您问我,这是一个有点奇怪的选择)。
https://stackoverflow.com/questions/27425766
复制相似问题