Python中以更简洁的方式处理异常,使用装饰器

在Python中以更简洁的方式处理异常,使用装饰器

在Python中处理异常在某些情况下会变得重复和难看,我们可以用装饰器来解决这个问题。

Python中的函数

Python中的函数是第一类对象,这意味着它们可以被分配给一个变量,作为参数传递,并从另一个函数中返回,并存储在任何数据结构中。

def example_function():
    print("调用示例函数")
some_variable = example_function

some_variable()

正如你所看到的,我们已经将example_function分配给some_variable,这使得some_variable可以被调用。下面的输出将是。

例子函数被调用 装饰器

函数的第一类对象属性帮助我们使用Python中Decorators的概念。装饰器是以另一个函数为参数的函数,它使我们能够把我们的逻辑放在参数函数执行的开始和结束处。

def decorator_example(func):
    print("Decorator called")

    def inner_function(*args, **kwargs):
            print("调用该函数")
            func(*args, **kwargs)
            print("函数的执行已经结束")
    return inner_function
@decorator_example
def some_function():
    print("正在执行函数")
    # 函数的逻辑在这里

正如你所看到的,我们是通过在需要作为参数传递给Decorator函数的函数之上使用@decorator_example来使用装饰器的。在这种情况下,some_function将被作为参数传给decorator_example。上述片段的输出将是。


装饰器被调用
调用该函数
执行该函数
函数的执行结束
使用装饰器处理错误

你可以将Decorators用于相当多的目的,如记录、验证或任何其他需要放在多个函数中的普通逻辑。装饰器可以用于许多领域,其中之一就是异常处理。

让我们举个例子,这类函数需要处理相同的异常。 我们将举一个计算面积的简单例子。如果一个不支持的类型作为参数被传递,我们将打印错误,在这种情况下,参数是一个字符串。

错误不应该无声地传递。 除非明确地消音。

通常的做法是将所有这些函数放在一个 try-catch 中,有点像这样。


def area_square(length):
    try:
        print(length**2)
    except TypeError:
        print("area_square只接受数字作为参数")


def area_circle(radius):
    try:
        print(3.142 * radius**2)
    except TypeError:
        print("area_circle只接受数字作为参数")


def area_rectangle(length, breadth):
    try:
        print(length * breadth)
    except TypeError:
        print("area_rectangle only takes numbers as the argument")
        

现在,这看起来是重复的,我们应该尽量避免。因此,我们可以在这里使用装饰器的魔力,并观察到这样的代码看起来干净多了。一个干净的代码会有很大的帮助。


def exception_handler(func):
    def inner_function(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except TypeError:
            print(f"{func.__name__} only takes numbers as the argument")
    return inner_function


@exception_handler
def area_square(length):
    print(length * length)


@exception_handler
def area_circle(radius):
    print(3.14 * radius * radius)


@exception_handler
def area_rectangle(length, breadth):
    print(length * breadth)


area_square(2)
area_circle(2)
area_rectangle(2, 4)
area_square("some_str")
area_circle("some_other_str")
area_rectangle("some_other_rectangle")
The output of the following will be:

4
12.568
8
area_square only takes numbers as the argument
area_circle only takes numbers as the argument
area_rectangle only takes numbers as the argument

下面的输出将是。

4
12.568
8
area_square只接受数字作为参数
area_circle只接受数字作为参数
area_rectangle只接受数字作为参数

我们可以通过自定义异常来扩展在异常处理程序中引发错误的能力,并进一步扩展其用途。这是其中一个例子,它使我们能够干净地处理异常。

本文由 mdnice 多平台发布

猜你喜欢

转载自blog.csdn.net/qq_40523298/article/details/127551140