首页 > Linux操作系统 > Linux操作系统 > Python Closures and Decorators (Part. 2)

Python Closures and Decorators (Part. 2)

原创 Linux操作系统 作者:jieforest 时间:2012-07-05 12:58:19 0 删除 编辑
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:


01.System Message: ERROR/3 (, line 11)
03.Unknown directive type "code".
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
16.>>> def greeter(greeting, what='world'):
17....     return "%s %s!" % (greeting, what)
19.>>> greeter = print_call(greeter)
20.>>> greeter("Hi")
21.Calling greeter with arguments:
22.args: ('Hi',)
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博客 ” ,链接:,如需转载,请注明出处,否则将追究法律责任。

下一篇: Metaclass in Python
请登录后发表评论 登录


  • 博文量
  • 访问量