Home  >  Q&A  >  body text

《python核心编程》中高级闭包和装饰器理解?

1.《python核心编程》的这段程序怎么理解?对于这个函数,书上说两个wraaped是闭包,但是不知道谁是自由变量。

2.代码:

from time import time


def logged(when):
    def log(f, *args, **kwargs):
        print '''Called: 
    function: %s 
    args: %r
    kwargs %r''' % (f, args, kwargs)

    def pre_logged(f):
        def wraper(*args, **kwargs):
                log(f, *args, **kwargs)
                return f(*args, **kwargs)
        return wraper

    def post_logged(f):
        def wrapped(*args, **kwargs):
            now = time()
            try:
                return f(*args, **kwargs)
            finally:
                log(f, *args, **kwargs)
                print "time delta: %s" % (time()-now)
        return wrapped

    try:
        return {"pre": pre_logged, "post": post_logged}[when]
    except KeyError, e:
        raise ValueError(e), 'must bre "pre" or "post"'


@logged("post")
def hello(name):
    print "Hello, ", name

hello('World!')
高洛峰高洛峰2741 days ago665

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:36:08

    The so-called closure refers to a function defined in a function. In fact, strictly speaking, all function definitions below your function logged above are closures

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:36:08

    About closures:
    When an inline function refers to a variable in the outer scope, we get a closure. Creating a closure must meet the following points at the same time:
    1. There must be an inline function. The external functions in the question are pre_logged and post_logged, and the corresponding embedded functions are wrapper and wrapped.
    2. The inline function must reference the variables of the external function. The question refers to external args, *kwargs parameters.
    3. The return value of an external function must be an embedded function. In the question, return wrapper, return wrapped is used to return.

    About decorators:
    Simply put, a decorator is a function that modifies the functionality of other functions. Logged in the question is a decorator, which is used to decorate the hello function you define.

    @logged("post")
    def hello(name):
        print "Hello, ", name
    
    hello('World!')
    

    You passed in "post" as the decorator parameter. According to: return {"pre": pre_logged, "post": post_logged}[when]
    The post_logged function is called. The function of post_logged is to print the time spent (time()- now)

    For a detailed explanation of decorators, please refer to "Python Advanced":
    Detailed Explanation of Decorators

    This entire book is well translated, I recommend you read it.

    reply
    0
  • Cancelreply