Python 你能用参数元组创建方法吗?

Python 你能用参数元组创建方法吗?,python,python-3.x,methods,parameters,parameter-passing,Python,Python 3.x,Methods,Parameters,Parameter Passing,您能在Python中执行类似的操作吗 def give_me_your_three_favorite_things_in_each_given_category( food=(first, second, third), color=(first, second, third)) println(f"Your favorite foods are {food.first}, {food.second} and {food.third}") p

您能在Python中执行类似的操作吗

def give_me_your_three_favorite_things_in_each_given_category(
    food=(first, second, third), 
    color=(first, second, third))
    println(f"Your favorite foods are {food.first}, {food.second} and {food.third}")
    println(f"Your favorite colors are {color.first}, {color.second} and {color.third}")

give_me_your_three_favorite_things_in_each_given_category(
    food=(first="pizza", second="pasta", third="ice cream"),
    color=(first="black", second="blue", third="green")
预期输出:
“你最喜欢的食物是比萨饼、意大利面和冰淇淋”
“你最喜欢的颜色是黑色、蓝色和绿色”

当然- 您将按照以下方式进行操作:

def give_me_your_three_favorite_things_in_each_given_category(food, color):
    first_food, second_food, third_food = food
    print(f"Your favorite foods are {first_food}, {second_food}, {third_food}")
    first_color, second_color, third_color = color
    print(f"Your favorite colors are {first_color}, {second_color}, {third_color}")
您可以在这里看到,我们接收元组作为参数,然后将它们解包

然后可以使用

give_me_your_three_favorite_things_in_each_given_category(
food=("pizza", "pasta", "ice cream"),
color=("black", "blue", "green"))
还可以使用命名元组,以便元组中的每个值都有名称:

from collections import namedtuple
Food = namedtuple("Food", ("first", "second", "third"))
Color = namedtuple("Color", ("first", "second", "third"))
give_me_your_three_favorite_things_in_each_given_category(
    food=Food(first="pizza", second="pasta", third="ice cream"),
    color=Color(first="black", second="blue", third="green")
)

使用口述<代码>定义…(食物…):println(f“…{food['first']}…”),和
给予…(food={'first':'pizza',…})
?这回答了你的问题吗@deceze我希望有一个指定所需参数数量的方法。您和maor10的答案很好,但如果您希望此方法的用户确切地知道要传递多少个参数,以及这些参数的确切含义,则答案不正确。@Stanislaw这到底意味着什么?@Stanislaw您的帖子显示了一堆无效代码。现在还不清楚哪一部分对你来说是重要的,以便得到更紧密的实施,或者这一切是否只是一个坏例子。正如我所评论的,为什么没有dicts?dicts在这里也不是正确的解决方案-您永远不会将dicts用于具有已知参数的数据模型。如果您希望使用参数名称,可以创建一个数据类或NamedTupleFood,这样您就可以从集合中导入NamedTupleFood=NamedTupleFood(“Food”)、((“first”、“second”、“third”)@maor10很有趣,您可以准确地理解我的问题:d