裝飾器 *arg **args

用 * 收集位置參數(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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容