python - 变长参数
变长参数即参数个数不确定、参数类型不定的函数。
元组变长参数:适用于位置参数的不固定,但是在函数中使用这些参数时无需知道这些参数的名字的场合。元组变长参数用星号“ * ”表示。
字典变长参数:适用于位置参数的不固定,而且在函数中使用这些参数时需要知道这些参数的名字的场合。字典变长参数用星号“ ** ”表示。
# 元组变长参数
def message(msg, *args):
for arg in args:
print(msg + ' comes from ' + arg)
if __name__ == '__main__':
message('jerry', 'Chongqing', 'Beijing', 'Shanghai')
# jerry comes from Chongqing
# jerry comes from Beijing
# jerry comes from Shanghai
# 字典变长参数
def message(**kwargs):
if 'price' in kwargs:
price = int(kwargs['price'])
if price >= 50:
print('价格太昂贵,买不起!')
else:
print('价格还能接受,可以考虑!')
else:
print('无价之宝!')
if __name__ == '__main__':
message(price=200)
message(price=10)
message(title='北京欢迎您!')
# 价格太昂贵,买不起!
# 价格还能接受,可以考虑!
# 无价之宝!