导语:
本文主要介绍了关于Python如何传递任意数量的实参的相关知识,希望可以帮到处于编程学习途中的小伙伴
传递任意数量的实参
在形参前加一个*,Python会以形参的名字创建一个空元组,并将所有接收到的值放入这个元组中 :
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings: ")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushroom', 'green peppers', 'extra cheese')
不管函数收到多少实参,这种语法都管用。
1. 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')
运行结果:
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushroom
- green peppers
- extra cheese
2. 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
profile = dict()
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physic')
print(user_profile)
形式参数**user_info 中的两个星号导致 python 创建一个名为 user_info 的空字典。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python开发中如何使用PyQt5?11/28
- ♥ Python-split()函数使用及简单实现09/10
- ♥ python单例使用详解01/08
- ♥ 如何将文件存储在python程序的目录中09/22
- ♥ 如何使用python保存文件后缀11/07
- ♥ python中装饰器的实际使用12/11
内容反馈