【问题标题】:Python returns None at closure while using decoratorsPython 在使用装饰器时在关闭时返回 None
【发布时间】:2020-02-07 22:05:55
【问题描述】:

问题在于,如果第二个数字不为零,则内部函数返回 None 而不是产生输出!

为什么它不能充当普通的装饰器?

代码:

def check(fun):
    def inner_fun(a,b):
        if b == 0:
            print("0 is not valid")
            return
        fun(a,b)
    return inner_fun  #returns None

def divide(a,b):
    return a / b

divide = check(divide)

print(divide(5, 0))

输出: 0 is not valid None

【问题讨论】:

  • 你应该在装饰器中返回你的包装函数调用,即return fun(a,b) 以获得你想要的

标签: python-decorators python-3.7


【解决方案1】:

内部函数没有返回您期望的值,因为...它没有return。相反,它隐式返回 None,就像 Python 函数在到达控制流结束时所做的那样。

您可以编辑内部函数以在正常情况下返回f(a, b)


def check(fun):
   def inner_fun(a,b):
        if b == 0:
            print("0 is not valid")
            return       # implicitly returns None
        return fun(a,b)  # note return
    return inner_fun

【讨论】:

  • 在不执行if语句时也返回None
  • 这是因为在原来的情况下,inner_func 计算 f(a, b)但不返回计算值。
  • 太棒了!如果这回答了您的问题,请参阅此帮助中心主题:What should I do when someone answers my question?
猜你喜欢
  • 2014-06-27
  • 1970-01-01
  • 2014-08-28
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2016-05-01
相关资源
最近更新 更多