最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)partial改變方法默認(rèn)參數(shù)

 更新時(shí)間:2014年08月18日 11:10:05   投稿:shichen2014  
這篇文章主要介紹了Python實(shí)現(xiàn)partial改變方法默認(rèn)參數(shù),需要的朋友可以參考下

在Python的標(biāo)準(zhǔn)庫中,functools庫中有很多對(duì)方法有操作的封裝功能,partial Objects就是其中之一,他可以實(shí)現(xiàn)對(duì)方法參數(shù)默認(rèn)值的修改。本文就以實(shí)例代碼說明這一功能。

下面就看下簡(jiǎn)單的應(yīng)用測(cè)試實(shí)例。具體代碼如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu

'''
functools 中Partial可以用來改變一個(gè)方法默認(rèn)參數(shù)
1 改變?cè)心J(rèn)值參數(shù)的默認(rèn)值
2 給原來沒有默認(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ì)象是沒有 __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的文檔信息了
'''

這樣如果我們使用一個(gè)方法總是需要默認(rèn)幾個(gè)參數(shù)的話就可以,先做一個(gè)封裝然后不用每次都設(shè)置相同的參數(shù)了。

希望本文所述方法對(duì)大家的Python程序設(shè)計(jì)有一定的借鑒與幫助價(jià)值。

相關(guān)文章

最新評(píng)論

定南县| 科技| 阿鲁科尔沁旗| 郁南县| 潮安县| 章丘市| 历史| 凤城市| 南陵县| 临朐县| 莱芜市| 哈巴河县| 巴塘县| 晋中市| 赤峰市| 金门县| 永顺县| 克东县| 霞浦县| 莱阳市| 东明县| 韶关市| 宁德市| 清水河县| 河北省| 二连浩特市| 望江县| 湖州市| 黔西| 梁平县| 南京市| 嘉义市| 永川市| 宜兴市| 班玛县| 宁德市| 阳东县| 资阳市| 祁连县| 偏关县| 三明市|