Python希望在参数列表的末尾使用任意参数,但是如果我们拥有默认参数并为其分配了值,则在此之前。 如何传递参数以匹配参数。 问题是,不必为sales_man参数传递参数,并且必须打印未知参数。
def pizzas(size, sales_man='unknown', *toppings):
print(f'your order is accepted for the pizza size: {size} by {sales_man}'
f'\nPlease check your toppings as below: ')
for topping in toppings:
print(f'- {topping}')
pizzas('medium', 'cheesy', 'Bacon', 'pepporni', 'Pineapple')
答案 0 :(得分:0)
将def
更改为:
def pizzas(size, *toppings, sales_man='unknown')
然后sales_man
可以作为关键字参数而不是位置参数传递:
pizzas('medium', 'cheesy', 'Bacon', 'pepporni', 'Pineapple')
输出:
your order is accepted for the pizza size: medium by unknown
Please check your toppings as below:
- cheesy
- Bacon
- pepporni
- Pineapple
输入:
pizzas('medium', 'cheesy', 'Bacon', 'pepporni', 'Pineapple', sales_man="Man")
输出:
your order is accepted for the pizza size: medium by Man(...)
答案 1 :(得分:0)
您只是不能这样做。每次调用该函数时,都必须提供该默认值(这违背了使用默认值开头的目的),或者将默认参数移到定义的末尾,并在调用中明确提及它,如下所示:
def a(b, *c, d=5):
...
a(1, 2,3,4,5, d=6)
答案 2 :(得分:0)
您只是不能这样做。相反,您可以尝试---
def pizzas(size, sales_man, *toppings):
if sales_man == None:
sales_man = 'unknown'
print("sales_man :: " + sales_man)
print(f'your order is accepted for the pizza size: {size} by {sales_man}'f'\nPlease check your toppings as below: ')
for topping in toppings:
print(f'- {topping}')
pizzas('medium', None, 'cheesy', 'Bacon', 'pepporni', 'Pineapple')
或
将方法签名更改为--- def pizzas(size, *toppings, sales_man='unknown'):
如果您想通过 sales_man ,则可以将其称为
pizzas('medium','cheesy', 'Bacon', 'pepporni', 'Pineapple', sales_man="Pawan")
或者如果您不想通过 sales_man ,则可以将其称为
pizzas('medium','cheesy', 'Bacon', 'pepporni', 'Pineapple')