Python Closures and Decorators (Part. 2)

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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/301743/viewspace-734619/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值