python 语法

Posted xuyuchen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 语法相关的知识,希望对你有一定的参考价值。

4.7.3. Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))
Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are 慿eyword-only? arguments, meaning that they can only be used as keywords rather than positional arguments.

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
earth/mars/venus
>>> concat("earth", "mars", "venus", sep=".")
earth.mars.venus
4.7.4. Unpacking Argument Lists
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state=a stiff, action=voom):
...     print("-- This parrot wouldn‘t", action, end= )
...     print("if you put", voltage, "volts through it.", end= )
...     print("E‘s", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin‘ demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldnt VOOM if you put four million volts through it. Es bleedin demised !

 

以上是关于python 语法的主要内容,如果未能解决你的问题,请参考以下文章

在下面的代码片段中的剩余 ='passthrough' 处的代码中出现语法错误

常用python日期日志获取内容循环的代码片段

python 有用的Python代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

[Python]常用代码块