1、使用位置实参
若要使函数接受不同类型的实参,则必须将接受任意数量实参的形参放在函数定义的最后。首先,Python匹配位置实参和关键词实参,然后将剩余的实参收集到最后一个形参中。
>>> def person(city, *args):
... print('city: ' + city + ', other args:')
... for value in args:
... print(value)
...
>>> person('beijing', 'name', 'age', 'tel')
city: beijing, other args:
name
age
tel
2、使用关键字实参
有时需要接受任意数量的实际参数,但是不知道传递给函数的信息是什么样的。在这种情况下,可以将函数写成可以接受任意数量的键值对。一个例子是创建用户介绍:知道会收到关于用户的信息,但是你不确定会是什么样的信息。
>>> def person(city, *args):
... print('city: ' + city + ', other args:')
... for value in args:
... print(value)
...
>>> person('beijing', 'name', 'age', 'tel')
city: beijing, other args:
name
age
tel
以上就是python在函数中传递实参的方法,希望对大家有所帮助。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有