国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現partial改變方法默認參數

2020-02-23 05:40:20
字體:
來源:轉載
供稿:網友

在Python的標準庫中,functools庫中有很多對方法有操作的封裝功能,partial Objects就是其中之一,他可以實現對方法參數默認值的修改。本文就以實例代碼說明這一功能。

下面就看下簡單的應用測試實例。具體代碼如下:

#!/usr/bin/env python# -*- coding: utf-8 -*-#python2.7x#partial.py#authror: orangleliu'''functools 中Partial可以用來改變一個方法默認參數1 改變原有默認值參數的默認值2 給原來沒有默認值的參數增加默認值'''def foo(a,b=0) :  '''  int add'  '''  print a + b#user default argumentfoo(1)#change default argument oncefoo(1,1)#change function's default argument, and you can use the function with new argumentimport functoolsfoo1 = functools.partial(foo, b=5) #change "b" default argumentfoo1(1)foo2 = functools.partial(foo, a=10) #give "a" default argumentfoo2()'''foo2 is a partial object,it only has three read-only attributesi will list them'''print foo2.funcprint foo2.argsprint foo2.keywordsprint dir(foo2)##默認情況下partial對象是沒有 __name__ __doc__ 屬性,使用update_wrapper 從原始方法中添加屬性到partial 對象中print foo2.__doc__'''執行結果:partial(func, *args, **keywords) - new function with partial application  of the given arguments and keywords.'''functools.update_wrapper(foo2, foo)print foo2.__doc__'''修改為foo的文檔信息了'''

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

希望本文所述方法對大家的Python程序設計有一定的借鑒與幫助價值。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安溪县| 宜良县| 静安区| 镇赉县| 灵宝市| 河间市| 沈丘县| 昆明市| 长寿区| 延川县| 凌源市| 寻乌县| 浦东新区| 舞阳县| 景东| 开阳县| 麻城市| 米泉市| 靖安县| 临湘市| 女性| 五寨县| 沅江市| 永善县| 淄博市| 宣化县| 石狮市| 诏安县| 巴彦县| 华安县| 乌审旗| 张家港市| 枝江市| 桃园市| 武宣县| 芜湖市| 南靖县| 芜湖市| 津南区| 木里| 彩票|