effective python讀書筆記——數(shù)量可變的參數(shù)
def show(message,value):
? ? #value用于存放數(shù)值信息,若為空則區(qū)別對待
? ? if not value:
? ? ? ? print("empty")
? ? else:
? ? ? ? value_str=','.join(str(x) for x in value)
? ? ? ? #join函數(shù):str.join(sequence),返回通過指定字符連接序列中元素后生成的新字符串
? ? ? ? #此處用逗號連接()中的每個元素
? ? ? ? print(f'{message} : {value_str}')
show('hello',[1,2,3])
show('hello',[])
#但這需要傳遞空列表,顯得多余,而且有點亂
def show_1(message,*value):#帶星號的參數(shù)可以接受任意數(shù)量的值
? ? if not value:
? ? ? ? print("empty")
? ? else:
? ? ? ? value_str=','.join(str(x) for x in value)
? ? ? ? print(f'{message} : {value_str}')
show_1('hi',1,2,3)
show_1('hi')
#如果想以列表的形式傳入
a_list=[22,11,33]
show_1('wow',*a_list)
'''
注意:
1,使用此方法時,程序會把這些參數(shù)轉化為一個元組,然后傳給參數(shù)
程序必須把生成器中的值迭代完
如果參數(shù)過多可能導致耗費大量內存而崩潰
2,當要添加新變量而修改函數(shù)時,需要更新函數(shù)的操作,避免把需要給新變量的
參數(shù)傳給了參數(shù)可變的*參數(shù)
'''
