星号只在定义函数(允许使用不定数目的参数)或者调用时才有用
一、(*)的使用
有时候需要让用户提供任意多的参数,这就需要用到收集参数。
星号的意思就是,收集多余的位置参数,如果不提供收集的元素,params 就是个空元祖
参数收集的逆过程:是在调用,而不是在定义时使用
二、(**)的使用
处理关键字参数的 “收集” 操作,返回的是字典而不是元祖
参数收集逆过程:
三、练习使用参数
字典的格式化字符串,在转换符中 % 字符后面可以加上键(使用圆括号括起来)
def story(**kwds):
return "Once upon a time,there was a " \ # 换行
'%(job)s called %(name)s.' % kwds # 字典的格式化字符
def power(x,y,*others):
if others:
print("Received redundant parameters",others)
return pow(x,y)
def interval(start,stop = None,step = 1):
'Imitates range() for step > 0'
if stop is None:
start,stop = 0,start;
result = []
i = start
while i<stop:
result.append(i)
i +=step
return result
print(story(job='king',name='Gumby'))
print(power(2,3,'Hello World !'))
print(interval(10))