python args i_Python中函数参数 *args 和 **kwargs

普通参数,即在调用函数时必须按照准确的顺序来进行参数传递。

默认参数,即参数含有默认值,在调用函数时可以进行参数传递,若没有进行参数传递则使用默认值,要注意,默认参数必须在普通参数的右侧(否则解释器无法解析)。

元组参数,即 *args,参数格式化存储在一个元组中,长度没有限制,必须位于普通参数和默认参数之后。

字典参数,即 **kwargs,参数格式化存储在一个字典中,必须位于参数列表的最后面。

普通参数

deffun(name):print('Hello', name)

fun('World')#Hello World

默认参数

def fun(name, age=1):print('Hello', name, age, '年')

fun('World') #Hello World 1 年

元组参数

def fun(name, age=1, *args):print('Hello', name, age, '年') #Hello World 1 年

print(args) #('I', 'love', 'it')

for i inargs:print(i)

fun('World', 1, 'I', 'love', 'it')

I

love

it

字典参数

def fun(name, age=1, *args, **kwargs):

print('Hello', name, age, '年') # Hello World 1 年

print(args) # ('I', 'love', 'it')

for i in args:

print(i)

print(kwargs) # {'my': 'jack', 'like': 'girl'}

for m in kwargs:

print(m, ':', kwargs[m])

fun('World', 1, 'I', 'love', 'it', my='jack', like='girl')

Hello World 1 年

('I', 'love', 'it')

I

love

it

{'my': 'jack', 'like': 'girl'}

my : jack

like : girl

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值