美文网首页
Python中不定长参数

Python中不定长参数

作者: MatsuiRakuyo | 来源:发表于2018-01-15 14:33 被阅读0次

测试输入如下,一个tuple,一个dict

lls = (78, 'stupid')
dds = dict(k1=1, k2=2, k3=3, name='stupid', num=76)

元组传入固定参数函数

通过*拆包

def unpack(num, word):
    print('hope num...{}'.format(num))
    print('hope stupid..'+word)
    
unpack(*lls)

输出如下:

hope num...78
hope stupid..stupid


不定长参数*args

传入元组时仍当作单个参数处理,同上拆包

def unpack2(*content):
    print(repr(content))
    print(', '.join('hope num...{}'.format(num) for num in content))
    unpack2(lls)#((78, 'stupid'),)

值得注意的是

    #unpack2(*lls, 96) #SyntaxError: only named arguments may follow *expression
    unpack2(96, *lls) # 拆包符号仅能作最后一个参数
    unpack2(*(lls+(1,))) #Solution

引用StackOverFlow的一篇回答

只允许星号表达式作为参数列表中的最后一项。这将简化拆包代码,并使得允许将星号表达式分配给一个迭代器。这种行为被拒绝了,因为这太令人吃惊了。(违反了'最少惊讶原则')

但这种情况只会出现在Python2中。
Python3有“仅限关键字参数”
>>> def f(a, *, b):
··· return a, b
···
>>> f(1, b=2)
(1,2)

不定长参数/dict的拆包表达式:**args

**dict将每个键值对元素作为单个元素作为参数传入。

**dict放在形式参数末尾,键值对与其他形式参数名匹配,剩余的存入形参dict。

def depack(func):
    def unpack3(name, num, **content):
        print(repr(content)) #{'k3': 3, 'k2': 2, 'k1': 1}
        print(', '.join(name*time for name,time in content.items())) #k3k3k3, k2k2, k1
        func(num, name)
    return unpack3

@depack
def unpack(num, word):
    print('hope num...{}'.format(num)) #hope num...76
    print('hope stupid..'+word) #hope stupid..stupid

unpack(**dds)

输出如下:

{'k3': 3, 'k2': 2, 'k1': 1}
k3k3k3, k2k2, k1
hope num...76
hope stupid..stupid

end

相关文章

  • Python中不定长参数

    测试输入如下,一个tuple,一个dict 元组传入固定参数函数 通过*拆包 输出如下: hope num...7...

  • python基础-day2

    不定参数(变长参数 ) ado使用 ... 表示变长参数,那py呢?python自定义函数中有两中不定长参数,第一...

  • python中的*args和**kwargs有什么区别

    python中的*args和**kwargs 都是属于不定长参数,那么他们之间有什么区别呢? args:当必备参数...

  • Python中的*args和**kwargs

    在Python中设置一个函数时,常见的参数类型分为:位置参数、默认参数、关键字参数、不定长参数。当我们不明确所定义...

  • python参数

    python中参数传递有顺序传递,关键词传递,默认参数和不定长参数四种形式 顺序传递 顺序传递就是按照形参的顺序依...

  • 第八章:函数

    python参数有四个概念 必须参数 关键字参数 默认参数 不定长参数 1)必须参数 和c、c++参数调用类似,需...

  • python基础函数

    python课程总结(2) [TOC] 函数的四种类型 全局变量 缺省参数 传参方式 不定长参数 函数的注意事项 ...

  • python-函数-不定长参数

    不定长参数 arg2是可选的,除了必须的参数arg1,其余的参数都放在arg2中 执行结果 如果参数只有一个(如a...

  • Java学习 Day7

    1.动态参数(不定长参数): 只能作为方法的参数。参数的个数不定。 语法:数据类型...变量名; (1)不定长参数...

  • 二维数组

    1.动态参数(不定长参数): 只能作为方法的参数。参数的个数不定。 语法:数据类型...变量名; (1)不定长参数...

网友评论

      本文标题:Python中不定长参数

      本文链接:https://www.haomeiwen.com/subject/yzzroxtx.html