【问题标题】:How to use multiple decorator to a function and chain them together?如何将多个装饰器用于一个函数并将它们链接在一起?
【发布时间】:2021-07-15 09:54:39
【问题描述】:

如何在 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

【问题讨论】:

  • 在给出预期结果的同时,也请给出实际结果,这样我们就不用跑coed就可以得到了
  • check_zero_error 在 check_numerator 之前执行,所以这很正常,2 不是 0,所以你尝试除法,然后第二个装饰器交换它们,你得到错误

标签: python function python-decorators


【解决方案1】:
  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"

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多