Python中使用partial改變方法默認參數(shù)實例
來源:易賢網(wǎng) 閱讀:1050 次 日期:2015-04-30 14:02:46
溫馨提示:易賢網(wǎng)小編為您整理了“Python中使用partial改變方法默認參數(shù)實例”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了Python中使用partial改變方法默認參數(shù)實例,本文直接給出使用實例,代碼中包含詳細注釋,需要的朋友可以參考下

Python 標準庫中 functools庫中有很多對方法很有有操作的封裝,partial Objects就是其中之一,他是對方法參數(shù)默認值的修改。

下面就看下簡單的應用測試。

代碼如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

#python2.7x

#partial.py

#authror: orangleliu

'''

functools 中Partial可以用來改變一個方法默認參數(shù)

1 改變原有默認值參數(shù)的默認值

2 給原來沒有默認值的參數(shù)增加默認值

'''

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)

##默認情況下partial對象是沒有 __name__ __doc__ 屬性,使用update_wrapper 從原始方法中添加屬性到partial 對象中

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的文檔信息了

'''

更多信息請查看IT技術專欄

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:Python中使用partial改變方法默認參數(shù)實例

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網(wǎng)