python函數參數*args**kwargs用法執行個體

來源:互聯網
上載者:User
代碼如下:


#coding=utf8
__author__ = 'Administrator'

# 當函數的參數不確定時,可以使用*args和**kwargs。*args沒有key值,**kwargs有key值

def fun_var_args(farg, *args):
print 'args:', farg
for value in args:
print 'another arg:',value

# *args可以當作可容納多個變數組成的list或tuple
fun_var_args(1, 'two', 3, None)

#args: 1
#another arg: two
#another arg: 3
#another arg: None


def fun_var_kwargs(farg, **kwargs):
print 'args:',farg
for key in kwargs:
print 'another keyword arg:%s:%s' % (key, kwargs[key])

# myarg1,myarg2和myarg3被視為key, 感覺**kwargs可以當作容納多個key和value的dictionary
fun_var_kwargs(1, myarg1='two', myarg2=3, myarg3=None)
# 輸出:
#args: 1
#another keyword arg:myarg1:two
#another keyword arg:myarg2:3
#another keyword arg:myarg3:None

def fun_args(arg1, arg2, arg3):
print 'arg1:', arg1
print 'arg2:', arg2
print 'arg3:', arg3

myargs = ['1', 'two', None] # 定義列表
fun_args(*myargs)

# 輸出:
#arg1: 1
#arg2: two
#arg3: None

mykwargs = {'arg1': '1', 'arg2': 'two', 'arg3': None} # 定義字典類型
fun_args(**mykwargs)

# 輸出:
#arg1: 1
#arg2: two
#arg3: None

# 兩者都有
def fun_args_kwargs(*args, **kwargs):
print 'args:', args
print 'kwargs:', kwargs


args = [1, 2, 3, 4]
kwargs = {'name': 'BeginMan', 'age': 22}
fun_args_kwargs(args,kwargs)
# args: ([1, 2, 3, 4], {'age': 22, 'name': 'BeginMan'})
# kwargs: {}

fun_args_kwargs(1,2,3,a=100)
#args: (1, 2, 3)
#kwargs: {'a': 100}

fun_args_kwargs(*(1,2,3,4),**{'a':None})
#args: (1, 2, 3, 4)
#kwargs: {'a': None}



  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.