这段代码是如何工作的?它来自渐变的“Data Science by Scratch”第 8 章。为什么我需要将一个函数包装在另一个函数中?有没有更易读的方法来实现这种异常处理?这是它的解释。
It is possible that certain step sizes will result in invalid inputs for our function. So we’ll need to create a “safe apply” function that returns infinity (which should never be the minimum of anything) for invalid inputs:
def safe(f):
"""return a new function that's the same as f,
except that it outputs infinity whenever f produces an error"""
def safe_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
return float('inf')
return safe_f
请您参考如下方法:
假设我们有一个像这样的简单函数:
def myfunc(n):
return 42/n
我们这样做:
print(myfunc(0))
我们得到这个:
Traceback (most recent call last):
File "gash.py", line 14, in <module>
print(myfunc(0))
File "gash.py", line 12, in myfunc
return 42/n
ZeroDivisionError: division by zero
现在我们这样做:
myfunc = safe(myfunc)
print(myfunc(0))
我们得到这个:
inf
我们第二次调用 safe(),它返回一个带有嵌入式异常处理的新函数。我们替换了 name “myfunc” 所指的内容,现在它指的是返回的函数。原来的myfunc没有丢失,在新的里面叫做f。
@safe 装饰器本质上与 myfunc = safe(myfunc)
