**keywords????
def cheeseshop(kind, *arguments, **keywords)
ex:
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")
当然它会按如下内容打印:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of LimburgerIt's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
解释:
调用函数时使用* **
test(*args) * 的作用其实就是把序列 args 中的每个元素,当作位置参数传进去。比如上面这个代码,如果 args 等于 (1,2,3) ,那么这个代码就等价于 test(1, 2, 3) 。
test(**kwargs) ** 的作用则是把字典 kwargs 变成关键字参数传递。比如上面这个代码,如果 kwargs 等于 {'a':1,'b':2,'c':3} ,那这个代码就等价于 test(a=1,b=2,c=3) 。
定义函数参数时使用* **
def test(*args):
...定义函数参数时 * 的含义又要有所不同,在这里 *args 表示把传进来的位置参数都装在元组 args 里面。比如说上面这个函数,调用 test(1, 2, 3) 的话, args 的值就是 (1, 2, 3) 。:
def test(**kwargs):
...类似的, ** 就是针对关键字参数和字典的了。 调用 test(a=1,b=2,c=3) 的话, kwargs 的值就是 {'a':1,'b':2,'c':3} 了。
1. 解压赋值:
* tuple ** dict *是解压元组 **解压字典
#coding:utf-8
p = [1, 2]
x,y = p
print(x,y)
record = [
('bar',1,2),
('foo','hello'),
('bar', 3, 4),
]
def do_bar(x,y):
print('bar',x,y)
def do_foo(s):
print('foo',s)
for name, *args in record:
if name == 'bar':
do_bar(*args) # 解压赋值
elif name == 'foo':
do_foo(*args)
2.占位符作用
data = ['bar',1,2,3,4,5,6,7,8,9,(2010,2012,2013,2014)]
_,*num,(*_1,year) = data
print(_)
print(num)
print(_1)
print(year)
3.解压
def test(a=1,b=2,c=3):
print(a,b,c)
def test1(**arr):
print(arr)
d = dict(a=4,b=5,c=6)
print(d) #{'a': 4, 'b': 5, 'c': 6}
test(*d) #a b c
test(**d)#4 5 6
test1(**d)