python *args **kwargs的区别 111111111111

ps 要使用 格式化字符串字面值 ,请在字符串的开始引号或三引号之前加上一个 f 或 F 。在此字符串中,你可以在 { 和 } 字符之间写可以引用的变量或字面值的 Python 表达式。

*args

When a function parameter starts with an asterisk, it allows for an arbitrary number of arguments, and the function takes them in as a tuple of values. Rewriting the above function:

In [3]:

def myfunc(*args):
    return sum(args)*.05

myfunc(40,60,20)

Out[3]:

6.0

Notice how passing the keyword "args" into the sum() function did the same thing as a tuple of arguments.

It is worth noting that the word "args" is itself arbitrary - any word will do so long as it's preceded by an asterisk. To demonstrate this:

In [4]:

def myfunc(*spam):
    return sum(spam)*.05

myfunc(40,60,20)

Out[4]:

6.0

**kwargs

Similarly, Python offers a way to handle arbitrary numbers of keyworded arguments. Instead of creating a tuple of values, **kwargsbuilds a dictionary of key/value pairs. For example:

In [5]:

def myfunc(**kwargs):
    if 'fruit' in kwargs:
        print(f"My favorite fruit is {kwargs['fruit']}")  # review String Formatting and f-strings if this syntax is unfamiliar
    else:
        print("I don't like fruit")
        
myfunc(fruit='pineapple')
My favorite fruit is pineapple

In [6]:

myfunc()
I don't like fruit

*args and **kwargs combined

You can pass *args and **kwargs into the same function, but *args have to appear before **kwargs

In [7]:

def myfunc(*args, **kwargs):
    if 'fruit' and 'juice' in kwargs:
        print(f"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}")
        print(f"May I have some {kwargs['juice']} juice?")
    else:
        pass
        
myfunc('eggs','spam',fruit='cherries',juice='orange')
I like eggs and spam and my favorite fruit is cherries
May I have some orange juice?

Placing keyworded arguments ahead of positional arguments raises an exception:

In [8]:

myfunc(fruit='cherries',juice='orange','eggs','spam')
  File "<ipython-input-8-fc6ff65addcc>", line 1
    myfunc(fruit='cherries',juice='orange','eggs','spam')
                                          ^
SyntaxError: positional argument follows keyword argument

As with "args", you can use any name you'd like for keyworded arguments - "kwargs" is just a popular convention.

That's it! Now you should understand how *args and **kwargs provide the flexibilty to work with arbitrary numbers of arguments!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值