赞
踩
函数默认值只会执行一次,在默认值为可变对象(如列表、字典以及大多数类实例)时很重要。函数会存储在后续调用中传递给它的参数。
- def f(a, L=[]):
- L.append(a)
- return L
-
- print(f('fofo '))
- print(f('Bonne nuit '))
- print(f('!!!!'))
执行结果如下:
['fofo ']
['fofo ', 'Bonne nuit ']
['fofo ', 'Bonne nuit ', '!!!!']
显然函数存储了后续调用传入的参数。若不希望调用之间共享默认值,可以使用关键字None
- def f(a,L=None):
- if L is None:
- L=[]
- L.append(a)
- return L
- print(f(123))
- print(f(1))
执行之后就不会有共享调用参数的情况。
关于参数函数的调用:
- def showpar(vule,stata = 'the striff',action = 'boom',type = 'Blue'):
- print('-- This showpar wouldn\'t',action,' ')
- print('if you put ',vule,'that will be show!')
- print('And show the type is ',type)
- print('--It\'s',stata,'!')
-
- showpar(1000)
- showpar(2000,action='fun')
当存在一个形式为**(name1)的最后一个形参时,它会接收一个字典,包括了除与已有形参相对应的关键字参数以外的所有关键字参数。这可以与一个形式为*(name2)一起接收一个包括除了已有形参列表以外的位置参数的元组形式的形参。
- 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)
- for kw in keywords:
- 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")
-
运行结果为:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
使用了for对导入的元组进行输出元组不一定要是字符串也可以是数字。
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。