functools
partial函数
偏函数,把一个函数的某些参数设置为默认值,返回一个新的函数,调用这个新函数会更加简单。
#coding=utf-8
import functools
def showarg(*args,**kw):
print (args)
print (kw)
p1 = functools.partial(showarg,1,2,3)
p1()
p1(7,8,9)
p1(a='python',b='cpp')
p2 = functools.partial(showarg,a=3,b=4,c=5)
p2()
p2(1,2)
p2(a='python',b='cpp')
(1, 2, 3)
{}
(1, 2, 3, 7, 8, 9)
{}
(1, 2, 3)
{'a': 'python', 'b': 'cpp'}
()
{'a': 3, 'c': 5, 'b': 4}
(1, 2)
{'a': 3, 'c': 5, 'b': 4}
()
{'a': 'python', 'c': 5, 'b': 'cpp'}
wraps函数
被装饰后的函数其实已经是另外一个函数(函数名等函数属性会发生变化)。添加后由于函数名和函数的__doc__
属性发生改变,对于结果有一些影响。
#coding=utf-8
import functools
def note(func):
'note function'
def wrapper():
'wrapper function'
print ('note something')
return func()
return wrapper
@note
def test():
'test function'
print('I am test')
test()
print(test.__doc__)
Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用。
#coding=utf-8
import functools
def note(func):
'note function'
#@functools.wraps(func)
def wrapper():
'wrapper function'
print ('note something')
return func()
return wrapper
@note
def test():
'test function'
print('I am test')
test()
print(test.__doc__)