python中编写无参数decorator
来源:互联网 发布:杨幂为李易峰打胎知乎 编辑:程序博客网 时间:2024/06/08 20:14
Python的 decorator 本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数。
使用 decorator 用Python提供的 @ 语法,这样可以避免手动编写 f = decorate(f) 这样的代码。
考察一个@log的定义:
def log(f): def fn(x): print 'call ' + f.__name__ + '()...' return f(x) return fn
对于阶乘函数,@log工作得很好:
@logdef factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))print factorial(10)
结果:
call factorial()...3628800
但是,对于参数不是一个的函数,调用将报错:
@logdef add(x, y): return x + yprint add(1, 2)
结果:
Traceback (most recent call last): File "test.py", line 15, in <module> print add(1,2)TypeError: fn() takes exactly 1 argument (2 given)
因为 add() 函数需要传入两个参数,但是 @log 写死了只含一个参数的返回函数。
要让 @log 自适应任何参数定义的函数,可以利用Python的 *args 和 **kw,保证任意个数的参数总是能正常调用:
def log(f): def fn(*args, **kw): print 'call ' + f.__name__ + '()...' return f(*args, **kw) return fn
现在,对于任意函数,@log 都能正常工作。
请编写一个@performance,它可以打印出函数调用的时间。
- ?不会了怎么办
计算函数调用的时间可以记录调用前后的当前时间戳,然后计算两个时间戳的差。
参考代码:
import timedef performance(f): def fn(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() print 'call %s() in %fs' % (f.__name__, (t2 - t1)) return r return fn@performancedef factorial(n): return reduce(lambda x,y: x*y, range(1, n+1))print factorial(10)
0 0
- python中编写无参数decorator
- Python进阶(六)-python编写无参数decorator
- Python编写带参数decorator
- Python进阶(八)-编写带参数decorator
- Python中带参数的decorator
- python中的decorator学习中......
- Python Decorators(二):Decorator参数
- Python Decorators(二):Decorator参数【转载】
- Python中若干概念和语法糖的廓清:参数、generator与decorator
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- Python decorator
- python decorator
- python decorator
- Python Decorator
- 猎头如何做大单,赚大钱?
- leetcode-Ugly Number
- Shiro系列之Shiro+Spring MVC整合
- simplenews项目学习(三)
- 简述MVC框架模式以及在你(ANDROID)项目中的应用
- python中编写无参数decorator
- 互联网后端基础设施概览
- Postman安装与入门讲解
- MST最小生成树 Kruskal算法
- HDU-1083 Courses(匈牙利算法)
- Longest Substring Without Repeating Characters
- C++调用函数是如何返回临时对象的
- linuxmint18/ubuntu16.04LTS上搭建cocos2d-x-3.14.1安卓开发环境
- leetcode-Happy Number