Home  >  Q&A  >  body text

python的装饰器返回值问题

为什么代码中得activate函数里面的wrapped函数中的try语句里面要return func呢

ringa_leeringa_lee2763 days ago450

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 11:53:09

    Because a decorated function is usually expected to return the same thing as when it is not decorated. What is returned there is the result of the undecorated function call. As for try, because the decorator needs to be cleaned up. The statement in finally will always be executed, whether an exception occurs or you say you are returning.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:53:09

    Decorators in Python are similar to Around advice in aspect-oriented programming (AOP) (for details, please refer to: http://docs.spring.io/spring/docs/2.0.8/reference/aop.html)
    When the code above calls the run function, it actually calls the wrapped function returned by the activate function, and the func variable in the wrapped function is the run function defined in test_simple. In other words, if you do not write "return func()" in the activate function, the run function defined in test_simple will not be called at all.
    If the above code is translated into JavaScript, the general meaning will be as follows:

    var run = activate(function(){
        // run函数中的代码
    })
    function activate(func) {
        return function() {
            // wrapped中的代码
            return func();        
        }
    }
    

    That is to say, the run function you called in test_simple is actually another function that has been replaced. This replaced function is the function returned in the activate function.

    reply
    0
  • Cancelreply