《python核心编程》中高级闭包和装饰器理解?
高洛峰
高洛峰 2017-04-18 10:34:08
0
2
687

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!')
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Peter_Zhu

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

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template