functools里面的函数
偏函数partial
在使用之前要先导入functools库,偏函数是在一次调用之后再次调用时相应的参数就不用再传了。
import functools
def showarg(*arg,**kwargs):
print(arg)
print(kwargs)
p1 =functools.partial(showage,1,2,3)
p1()
p1(4,5,6)
p1 =(a ='python',b='itcast')
如上图所示:在第一次调用偏函数之后之前传进去的值1,2,3一直在函数里面。
wraps函数
如果一个函数
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')
print(help(test))
此时调出来的说明文档是上面装饰器的说明文档,而不是下面test函数自带的函数。因为在调用test函数时,装饰器会自动运行。所以此时的help——test函数的说明文档的时候,会输出上面装饰器的说明文档。此时就需要wraps函数来保持调出说明文档的时候不会变化。
import functools
def note(func):
"note function"
#此时是用一个带有一个参数的装饰器,去装饰下面的wrapper函数此时输出的函数就会是装饰器装饰的函数。
@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__)