装饰器是一个返回函数的高阶函数。python
def logger(func): def wrapper(*args, **kw): print 'do {}'.format(func.__name__) func(*args, **kw) print 'finish' return wrapper @logger def add(x,y): print '{} + {} = {}'.format(x,y,x+y) add(3,5)
在函数执行前,打印一行日志do...
;函数执行结束,打印一行日志finish
。执行结果以下:app
do add 3 + 5 = 8 finish
计算时间函数
import time def timer(func): def wrapper(*args, **kw): t1 = time.time() func(*args,**kw) t2 = time.time() cost_time = t2 - t1 print 'cost time: {} s'.format(cost_time) return wrapper @timer def cost_time(sleep_time): time.sleep(sleep_time) cost_time(10)
def say_hello(country): def wrapper(func): def decorate(*args,**kw): if country == 'en': print 'hello' elif country == 'usa': print 'hi' else: return func(*args,**kw) return decorate return wrapper @say_hello("usa") def usa(): print 'i am from usa' @say_hello("en") def en(): print 'i am from england' usa() print '----------------------' en()
装饰器自己是一个函数,使用两层嵌套传参,执行结果以下:日志
hi i am from usa ---------------------- hello i am from england
__call__
和__init__
两个内置函数。__init__
:接收被装饰函数__call__
:实现装饰逻辑class logger(object): def __init__(self,func): self.func = func def __call__(self,*args,**kwargs): print 'the function {}() is running...'\ .format(self.func.__name__) return self.func(*args,**kwargs) @logger def say(something): print 'say {}!'.format(something) say('hello')
运行结果以下:code
the function say() is running... say hello!
__init__
:再也不接收被装饰函数,而是接收传入参数__call__
:接收被装饰函数,实现装饰逻辑class logger(object): def __init__(self,level='INFO'): self.level = level def __call__(self,func): def wrapper(*args,**kwargs): print '{level}: the function {func} () is running...'\ .format(level=self.level, func=func.__name__) func(*args,**kwargs) return wrapper @logger(level='WARNING') def say(something): print 'say {}!'.format(something) say('hello')
运行结果以下:orm
WARNING: the function say () is running... say hello!
def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s
power(x, n)
函数有两个参数:x
和n
,这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序依次赋值给参数x
和n
。ci
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
power(x, n)
函数有两个参数:x
和n
,若是想在不传入n
值时,默认计算x
的平方,此时能够将n
设为默认值2。it
def function(f_arg, *args): print f_arg, type(f_arg) print args, type(args) nums = ['a','b','c'] function(1,2,*nums)
定义可变参数时,须要在参数前面加一个*
号,可变参数的个数是可变的。在函数内部,参数*args
接收到的是一个tuple
。输出结果以下:io
1 <type 'int'> (2, 'a', 'b', 'c') <type 'tuple'>
def person(name,age,**kwargs): print 'name:',name,'age:',age,'other:',kwargs,type(kwargs) person('mark',30,city='shanghai')
**kwargs
容许将不定长度的键值对,做为参数传递给一个函数,关键字参数在函数内部自动组装为一个dict
。输出结果以下:function
name: mark age: 30 other: {'city': 'shanghai'} <type 'dict'>
def hi(): return 'hi friends' def function(func): print 'just test' print func() function(hi)
function()
函数将hi
函数做为参数接收,输出结果以下:
just test hi friends
>>> time.localtime() time.struct_time(tm_year=2019, tm_mon=8, tm_mday=21, tm_hour=14, tm_min=31, tm_sec=18, tm_wday=2, tm_yday=233, tm_isdst=0)
>>> time.ctime() 'Wed Aug 21 14:51:28 2019' >>> time.asctime() 'Wed Aug 21 14:51:34 2019'
>>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) '2019-08-21 14:35:02' >>> time.strftime('%a %b %d %H:%M:%S %Y',time.localtime()) 'Wed Aug 21 14:36:09 2019'
import time start = time.time() time.sleep(2) end = time.time() print end-start