python 接受输入两个参数 空格隔开_Python方法接受一个位置参数,但给出了两个位置参数...

当您将关键字参数传递给函数时,它将转换为字典。不是相反。在

args和kwargs的详细说明

*args表示函数/方法可以接受任意数量的位置参数,并将存储在名为args的列表中。在

**kwargs表示它可以接受任意数量的命名参数,并将存储在名为kwargs的字典中

还不清楚?让我举个例子(虽然很简单很天真)—# Suppose you want to write a function that can find the

# sum of all the numbers passed to it.

def sum(a, b):

return a + b

>>> sum(2, 3) # => 5

# Now this function can only find sum of two numbers, what

# if we have 3, 4 or more numbers, how would be go solving that.

# Easy let's take an array/list as an argument -

def sum(numbers):

total = 0

for number in numbers:

total += number

return total

# But now we'd have to call it like -

>>> sum([2, 3]) # => 5

>>> sum(2, 3) # => throws an error.

# That might be ok for some other programming languages, but not

# for Python. So python allows you to pass any number of

# arguments, and it would automatically store them into list

# called args (as a conventions, but it can be called

# anything else say 'numbers')

def sum(*numbers):

total = 0

for number in numbers:

total += number

return total

>>> sum(2, 3, 4) # => 9

# Viola!

类似地,kwargs用于自动将所有命名参数存储为字典。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值