Python Closures and Decorators (Part. 2)

jieforest發表於2012-07-05
In part 1, we looked at sending functions as arguments to other functions, at nesting functinons, and finally we wrapped a function in another function. We'll begin this part by giving an example implementation on the exercise I gave in part 1:

CODE:

01.System Message: ERROR/3 (, line 11)
02.
03.Unknown directive type "code".
04.
05... code:: python
06.>>> def print_call(fn):
07....   def fn_wrap(*args, **kwargs):
08....     print("Calling %s with arguments: \n\targs: %s\n\tkwargs:%s" % (
09....            fn.__name__, args, kwargs))
10....     retval = fn(*args, **kwargs)
11....     print("%s returning '%s'" % (fn.func_name, retval))
12....     return retval
13....   fn_wrap.func_name = fn.func_name
14....   return fn_wrap
15....
16.>>> def greeter(greeting, what='world'):
17....     return "%s %s!" % (greeting, what)
18....
19.>>> greeter = print_call(greeter)
20.>>> greeter("Hi")
21.Calling greeter with arguments:
22.args: ('Hi',)
23.kwargs:{}
24.greeter returning 'Hi world!'
25.'Hi world!'
26.>>> greeter("Hi", what="Python")
27.Calling greeter with arguments:
28.args: ('Hi',)
29.kwargs:{'what': 'Python'}
30.greeter returning 'Hi Python!'
31.'Hi Python!'
32.>>>So, this is at least mildly useful, but it'll get better! You may or may not have heard of closures, and you may have heard any of a large number of defenitions of what a closure is - I won't go into nitpicking, but just say that a closure is a block of code (for example a function) that captures (or closes over) non-local (free) variables. If this is all gibberish to you, you're probably in need of a CS refresher, but fear not - I'll show by example, and the concept is easy enough to understand: a function can reference variables that are defined in the function's enclosing scope.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-734619/,如需轉載,請註明出處,否則將追究法律責任。

相關文章