Python中使用partial改變方法默認(rèn)參數(shù)實(shí)例
Python 標(biāo)準(zhǔn)庫(kù)中 functools庫(kù)中有很多對(duì)方法很有有操作的封裝,partial Objects就是其中之一,他是對(duì)方法參數(shù)默認(rèn)值的修改。
下面就看下簡(jiǎn)單的應(yīng)用測(cè)試。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu
'''
functools 中Partial可以用來(lái)改變一個(gè)方法默認(rèn)參數(shù)
1 改變?cè)心J(rèn)值參數(shù)的默認(rèn)值
2 給原來(lái)沒(méi)有默認(rèn)值的參數(shù)增加默認(rèn)值
'''
def foo(a,b=0) :
'''
int add'
'''
print a + b
#user default argument
foo(1)
#change default argument once
foo(1,1)
#change function's default argument, and you can use the function with new argument
import functools
foo1 = functools.partial(foo, b=5) #change "b" default argument
foo1(1)
foo2 = functools.partial(foo, a=10) #give "a" default argument
foo2()
'''
foo2 is a partial object,it only has three read-only attributes
i will list them
'''
print foo2.func
print foo2.args
print foo2.keywords
print dir(foo2)
##默認(rèn)情況下partial對(duì)象是沒(méi)有 __name__ __doc__ 屬性,使用update_wrapper 從原始方法中添加屬性到partial 對(duì)象中
print foo2.__doc__
'''
執(zhí)行結(jié)果:
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
'''
functools.update_wrapper(foo2, foo)
print foo2.__doc__
'''
修改為foo的文檔信息了
'''
相關(guān)文章
python深度學(xué)習(xí)tensorflow訓(xùn)練好的模型進(jìn)行圖像分類(lèi)
這篇文章主要為大家介紹了python深度學(xué)習(xí)tensorflow訓(xùn)練好的模型進(jìn)行圖像分類(lèi)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Python大數(shù)據(jù)之從網(wǎng)頁(yè)上爬取數(shù)據(jù)的方法詳解
這篇文章主要介紹了Python大數(shù)據(jù)之從網(wǎng)頁(yè)上爬取數(shù)據(jù)的方法,結(jié)合實(shí)例形式詳細(xì)分析了Python爬蟲(chóng)爬取網(wǎng)頁(yè)數(shù)據(jù)的相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
教你使用Pandas直接核算Excel中的快遞費(fèi)用
文中仔細(xì)說(shuō)明了怎么根據(jù)賬單核算運(yùn)費(fèi).首先要確定運(yùn)費(fèi)規(guī)則,然后根據(jù)運(yùn)費(fèi)規(guī)則編寫(xiě)代碼,生成核算列(快遞費(fèi) = 省份*重量),最后輸入賬單,進(jìn)行核算.將腳本件生成EXE文件,就可以使用啦,需要的朋友可以參考下2021-05-05
python如何繪制極坐標(biāo)輪廓圖contourf
這篇文章主要介紹了python如何繪制極坐標(biāo)輪廓圖contourf問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
django-rest-swagger的優(yōu)化使用方法
今天小編就為大家分享一篇django-rest-swagger的優(yōu)化使用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
python利用opencv如何實(shí)現(xiàn)答題卡自動(dòng)判卷
由于工作需要,最近在研究關(guān)于如何通過(guò)程序識(shí)別答題卡的客觀題的答案,所以下面這篇文章主要介紹了python利用opencv如何實(shí)現(xiàn)答題卡自動(dòng)判卷的相關(guān)資料,需要的朋友可以參考下2021-08-08

