''' @Date: 2019-10-10 21:14:56 @LastEditors: 馮浩 @LastEditTime: 2019-10-20 22:38:16 '''
def func(*args): # just use "*" to collect all remaining arguments into a tuple
# 這裏的*是關鍵符號,args能夠替換爲其餘命名
# 更通常的函數定義方式是def fun(*args,**kwargs),
# 能夠在許多Python源碼中發現這種定義,
# 其中*args表示任何多個無名參數,它本質是一個元組tuple;
# **kwargs表示關鍵字參數,它本質上是一個字典dict。
numargs = len(args) print("參數數量: {0}".format(numargs)) for i, x in enumerate(args): print("參數 {0} 是: {1}".format(i, x)) print() func('a', 'b', 'c', {1: 'one', 2: 'two'}) func(('a', 'b', 'c')) func(['1', '2', '3']) print('-'*32) ''' 參數數量: 4 參數 0 是: a 參數 1 是: b 參數 2 是: c 參數 3 是: {1: 'one', 2: 'two'} 參數數量: 1 參數 0 是: ('a', 'b', 'c') 參數數量: 1 參數 0 是: ['1', '2', '3'] '''
def func_dict(**kwargs): print('傳入參數長度爲{0}, 類型爲{1}, 內容爲{2}'.format( len(kwargs), type(kwargs), kwargs) ) for key,value in kwargs.items(): print('鍵: {0}, 值: {1}'.format(key,value)) # 注意這裏變量不能爲數字,可是字典能夠. # 如1='one'不被容許
func_dict(one='一', two='二') ''' 傳入參數長度爲2, 類型爲<class 'dict'>, 內容爲{'one': '一', 'two': '二'} 鍵: one, 值: 一 鍵: two, 值: 二 '''