传递值或更改修饰函数的返回值

时间:2020-10-07 17:35:50

标签: python python-decorators

我有两个函数g(x)h(x),它们都具有相同的try-except语句,如下所示:

class Ex1(Exception):
    """Custom exception"""
    pass

def f(x):
    if x > 2:
        raise Ex1
    return x
    
def g(x):
    try:
        y = f(x)
    except Ex1:
        return "Custom exception raised"
    return y + 1

def h(x):
    try:
        y = f(x)
    except Ex1:
        return "Custom exception raised"
    return y + 2

print(g(3))

是否可以用修饰符替换try-exceptg(x)中的h(x),以避免代码重复?

基本上,我想特别指出的是,如果f(x)中引发了异常,则g(x)h(x)返回一个自定义字符串,否则从f(x)返回的值可以是在g(x)h(x)中用作变量。

1 个答案:

答案 0 :(得分:3)

这是一个简单的函数修饰符(改编自this文章),如果没有错误,则正常返回函数,如果引发异常,则返回自定义字符串

import functools

def exception(function):
    """
    A decorator that wraps the passed function and returns a custom string if there is an 
    error
    """
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except:
            return "Custom exception raised!"
    return wrapper

@exception
def f(a):
    """Simple example demonstrating the wrapper"""
    print(a + 1)

样品用量:

>>>f(1)
2
>>>f('spam')
'Custom exception raised!'

调用f(1)可以正常工作,但是f('spam')由于TypeError: can only concatenate str (not "int") to str而中断,并且exception装饰器中的try-except块返回Custom exception raised!"

其他资源: