码迷,mamicode.com
首页 > 编程语言 > 详细

python 语法

时间:2018-02-07 00:39:41      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:nal   tuple   turn   start   mil   return   multi   ble   seq   

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 语法

标签:nal   tuple   turn   start   mil   return   multi   ble   seq   

原文地址:https://www.cnblogs.com/xuyuchen/p/8424670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!