用 * 收集位置參數(shù)
In [91]: def print_args(*args):
...: print('傳入的位置參數(shù)會(huì)包含在一個(gè)元組里:',args)
...:
# 情景 1
In [92]: print_args(22,'192.168.1.10','yangge')
傳入的位置參數(shù)會(huì)包含在一個(gè)元組里: (22, '192.168.1.10', 'yangge')
# 情景 2
In [93]: li = [22,'192.168.1.10','yangge']
In [94]: print_args(li)
傳入的位置參數(shù)會(huì)包含在一個(gè)元組里: ([22, '192.168.1.10', 'yangge'],)
# 上面的這種方式是,每個(gè)實(shí)參對(duì)象作為元組的一個(gè)元素
# 玩點(diǎn)兒花活
In [95]: print_args(*li)
傳入的位置參數(shù)會(huì)包含在一個(gè)元組里: (22, '192.168.1.10', 'yangge')
In [102]: print_args(*'abc')
傳入的位置參數(shù)會(huì)包含在一個(gè)元組里: ('a', 'b', 'c')
# 這也就是傳說總元組解包的原理
# 把一個(gè)可迭代對(duì)象中的每個(gè)元素作為元組的每一個(gè)元素
用 ** 收集關(guān)鍵字參數(shù)
def print_kwargs(**kwargs):
print("接收的關(guān)鍵字參數(shù),會(huì)是一個(gè)字典:", kwargs)
print_kwargs(name='yangge')
接收的關(guān)鍵字參數(shù),會(huì)是一個(gè)字典: {'name': 'yangge'}
In [105]: print_kwargs(ip='192.168.1.10', port=22)
接收的關(guān)鍵字參數(shù),會(huì)是一個(gè)字典: {'ip': '192.168.1.10', 'port': 22}
# 同樣可以玩點(diǎn)兒花活
In [106]: dic = {'ip': '192.168.1.10', 'port': 22}
In [107]: print_kwargs(**dic)
接收的關(guān)鍵字參數(shù),會(huì)是一個(gè)字典: {'ip': '192.168.1.10', 'port': 22}
裝飾器
def outer(f):
def inner(*arg):
print("haha")
f()
print(arg)
print("haha")
return inner
@outer
def echo(*arg):
print("gg")
arg=[1,2,3]
echo(*arg)
def outer(f):
def inner(*arg,**args):
print("haha")
f()
print(arg,'and',args)
print("haha")
return inner
@outer
def echo(*arg,**args):
print("gg")
arg="helloworld"
echo(*arg,ip='192.168.1.10', port=22)