python中functools_functools模块2个常用函数
functools是python2.5被引人的,一些工具函數(shù)放在此包里,python3中增加了更多工具函數(shù),業(yè)務(wù)開發(fā)時(shí)大多情況下用不到,此處介紹使用頻率較高的2個(gè)函數(shù)。
partial函數(shù)(偏函數(shù))
這個(gè)函數(shù)在基礎(chǔ)教程篇介紹過,可查看偏函數(shù),partial函數(shù)可以把一個(gè)函數(shù)的某些參數(shù)預(yù)先設(shè)置默認(rèn)值,返回一個(gè)新的函數(shù),調(diào)用這個(gè)新函數(shù)會(huì)更簡(jiǎn)單。
# -*- coding: utf-8 -*-
import functools
def showarg(*args, **kw):
print(args)
print(kw)
p1=functools.partial(showarg, 1,2,3)
p1()
p1(4,5,6)
p1(a='python', b='dong')
p2=functools.partial(showarg, a=3,b='linux')
p2()
p2(1,2)
p2(a='python', b='dong')
D:python3installpython.exe D:/python/py3script/python66_2.py
(1, 2, 3)
{}
(1, 2, 3, 4, 5, 6)
{}
(1, 2, 3)
{'a': 'python', 'b': 'dong'}
()
{'a': 3, 'b': 'linux'}
(1, 2)
{'a': 3, 'b': 'linux'}
()
{'a': 'python', 'b': 'dong'}
Process finished with exit code 0
wraps函數(shù)
使用裝飾器時(shí),有一些細(xì)節(jié)需要被注意。例如,被裝飾后的函數(shù)其實(shí)已經(jīng)是另外一個(gè)函數(shù)了(函數(shù)名等函數(shù)屬性會(huì)發(fā)生改變)。添加后對(duì)測(cè)試結(jié)果有一些影響,例如:
# -*- coding: utf-8 -*-
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__)
D:python3installpython.exe D:/python/py3script/python66_2.py
note something
I am test
wrapper function
Process finished with exit code 0
所以,Python的functools包中提供了一個(gè)叫wraps的裝飾器來(lái)消除這樣的副作用。例如:
# -*- 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__)
D:python3installpython.exe D:/python/py3script/python66_2.py
note something
I am test
test function
Process finished with exit code 0
總結(jié)
以上是生活随笔為你收集整理的python中functools_functools模块2个常用函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang 指针
- 下一篇: IDEA mybatis-generat