標籤:sum delphi ecif sdn function print file spec usr
當要使函數接收元組或字典形式的參數 的時候,有一種特殊的方法,它分別使用*和**首碼 。這種方法在函數需要擷取可變數量的參數的時候特別有用。
[注意]
[1] 由於在args變數前有*首碼 ,所有多餘的函數參數都會作為一個元組儲存在args中 。如果使用的是**首碼 ,多餘的參數則會被認為是一個字典的健/值對 。
[2] 對於def func(*args):,*args表示把傳進來的位置參數儲存在tuple(元組)args裡面。例如,調用func(1, 2, 3) ,args就表示(1, 2, 3)這個元組 。
[3] 對於def func(**args):,**args表示把參數作為字典的健-值對儲存在dict(字典)args裡面。例如,調用func(a=‘I‘, b=‘am‘, c=‘wcdj‘) ,args就表示{‘a‘:‘I‘, ‘b‘:‘am‘, ‘c‘:‘wcdj‘}這個字典 。
[4] 注意普通參數與*和**參數公用的情況,一般將*和**參數放在參數列表最後。
[元組的情形]
#! /usr/bin/python# Filename: tuple_function.py# 2010-7-19 wcdjdef powersum(power, *args): ‘‘‘Return the sum of each argument raisedto specified power.‘‘‘ total=0 for i in args: total+=pow(i,power) return totalprint ‘powersum(2, 3, 4)==‘, powersum(2, 3, 4)print ‘powersum(2, 10)==‘, powersum(2, 10)######### output########powersum(2, 3, 4)==25powersum(2, 10)==100
[字典的情形]
#! /usr/bin/python# Filename: dict_function.py# 2010-7-19 wcdjdef findad(username, **args): ‘‘‘find address by dictionary‘‘‘ print ‘Hello: ‘, username for name, address in args.items(): print ‘Contact %s at %s‘ % (name, address)findad(‘wcdj‘, gerry=‘[email protected]‘, / wcdj=‘[email protected]‘, yj=‘[email protected]‘
在gvim中的輸出結果:
http://blog.csdn.net/delphiwcdj/article/details/5746560
Python在函數中使用*和**接收元組和列表