如何对一个函数使用多个装饰器并将它们链接在一起?

How to use multiple decorator to a function and chain them together?

如何在 Python 中创建两个装饰器来执行以下操作?

@check_zero_error
@check_numerator
def division(a, b):
    return a/b
如果分子小于分母,

'check_numerator' 将反转数字。

'check_zero_error' 将检查除零错误。

预期输出为:

division(1, 2)   # Output : 2.0

division(0, 2)   # Output : "Denominator can't be zero"
 
division(4, 1)   # Output : 4.0

division(5, 0)   # Output : "Denominator can't be zero"

我的代码如下,但没有得到预期的结果:

def check_zero_error(division_func):
    def inner(a, b):
        if b == 0:
            return "Denominator can't be zero"
        else:
            division_func(a, b)
    return inner

def check_numerator(division_func):
    def inner(a, b):
        if a < b:
            a, b = b, a
        division_func(a, b)
    return inner


@check_zero_error
@check_numerator
def division(a, b):
    return a/b
       

print(division(1, 2))  # Expected output : 2.0
print(division(0, 2))  # Expected output : "Denominator can't be zero"
print(division(4, 1))  # Expected output : 4.0
  1. 你的装饰器方法应该return除法的结果

    def check_zero_error(division_func):
        def inner(a, b):
            if b == 0:
                return "Denominator can't be zero"
            else:
                return division_func(a, b)
        return inner
    
    def check_numerator(division_func):
        def inner(a, b):
            if a < b:
                a, b = b, a
            return division_func(a, b)
        return inner
    
  2. 更改装饰器的顺序,首先 swap (check_numerator) 然后如果需要,然后用 check_zero_error

    检查分母
    @check_numerator
    @check_zero_error
    def division(a, b):
        return a / b
    

给予预期

print(division(1, 2))  # actual output : 2.0
print(division(0, 2))  # actual output : "Denominator can't be zero"
print(division(4, 1))  # actual output : 4.0
print(division(5, 0))  # actual output :  "Denominator can't be zero"