1.默认参数值
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)
这个函数可以通过几种不同的方式调用:
只给出必要的参数: ask_ok(‘Do you really want to quit?’)
给出一个可选的参数: ask_ok(‘OK to overwrite the file?’, 2)
或者给出所有的参数: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)
2.引入一个形如 **name 的参数时, 它接收一个字典,形如 *name它接收一个元组。
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])
它可以像这样调用:
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
3.一个最不常用的选择是可以让函数调用可变个数的参数。 这些参数被包装进一个元组(参见
元组和序列 ) 。 在这些可变个数的参数之前, 可以有零到多个普通的参数
>>> def concat(*args, sep="/"):
... return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'