Python自定义函数基础(2)

通常情况下,可变参数将在参数列表中的最后(含有默认参数的时候,默认参数在可变参数后面。另外,传入字典参数也在可变参数之后,因为字典参数也是一种可变参数)。
在可变参数后面的参数,只能以关键字实参的方式传递,而不能使用位置实参传递方式。
def concat(*args, sep="/"):
    return sep.join(args)
 
print(concat("earth", "mars", "venus"))
print(concat("earth", "mars", "venus",sep="."))

结果为:
>>>
===========RESTART: D:/python/pythonLearning/KeywordArguments.py ===========
earth/mars/venus
earth.mars.venus
(5)需要字典类型的参数“**”
下面例子中**keywords代表传入字典类型的参数,而且*一定要在**之前。
def cheeseshop(kind, *arguments, **keywords):
    print("--Do you have any", kind, "?")
    print("--I'm sorry, we're all out of", kind)
    for arg inarguments:
        print(arg)
  print("-" * 40)
    keys =sorted(keywords.keys())
    for kw in keys:
        print(kw,":", keywords[kw])

可以这样调用
    cheeseshop("Limburger", "It's very runny, sir.",

"It's really very, VERY runny, sir.",
          shopkeeper="Michael Palin",
          client="John Cleese",
          sketch="Cheese Shop Sketch")
当然结果如下:
        >>>
===========RESTART: D:/python/pythonLearning/KeywordArguments.py ===========
-- Do you haveany Limburger ?
-- I'm sorry,we're all out of Limburger
It's very runny,sir.
It's reallyvery, VERY runny, sir.
----------------------------------------
client : JohnCleese
shopkeeper :Michael Palin
sketch : CheeseShop Sketch
(6)Unpacking Argument Lists(python3.6帮助文档上用的这个词,必应翻译给的翻译是开箱的参数列表,我感觉应该是参数列表的拆包,不够下面还是用了开箱这个词,大家理解下)
        这是与之前把数据组合成list相反的操作,即把list中的数据进行开箱操作,把里面的数据全部取出来使用,有点不好理解,看个例子吧
 
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>> args=(3,6)
>>> list(range(*args))
[3, 4, 5]

>>>这里把args中的数据进行开箱操作,把里面的数据作为range的参数列表.很显然,这个开箱操作对于元组也是适用的.
 
另外,也可以对字典执行开箱操作,需要的是两个*号即可.
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": "fourmillion", "state": "bleedin' demised","action": "VOOM"}
parrot(**d)
 
结果为:
>>>
=========== RESTART:D:/python/pythonLearning/KeywordArguments.py ===========
-- This parrot wouldn't VOOM if you putfour million volts through it. E's bleedin' demised !
>>>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/97cd76b6a6d405fb7aea88d01d78d3de.html