You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Python类中处理任意数量菜系属性及输出的技术咨询

Python类中处理任意数量菜系属性及输出的技术咨询

嘿,很高兴你的初始代码能正常运行!不过先提个小细节:你原来的describe_restaurant()方法忘了加self参数,实际运行会报错,咱们调整的时候一起修正哈。

针对你说的餐厅需要支持多种菜系的需求,确实可以用*来接收任意数量的参数,下面是具体的调整方案:

步骤1:修改类的初始化方法

把cuisine_type改成*cuisine_types,这样它能接收任意数量的菜系参数,然后我们把这些参数存为一个列表(方便后续操作):

class Restaurant():
    def __init__(self, restaurant_name, *cuisine_types):
        self.restaurant_name = restaurant_name
        # 把接收的任意数量菜系转成列表存储
        self.cuisine_types = list(cuisine_types)

步骤2:调整描述方法的输出逻辑

现在菜系是一个列表了,我们可以根据列表长度来调整输出方式,让结果更友好:

def describe_restaurant(self):
        print(f"The name of the restaurant is {self.restaurant_name}")
        if len(self.cuisine_types) == 1:
            print(f"Our food menu specializes in {self.cuisine_types[0]}")
        else:
            # 用逗号连接多个菜系,最后加个"and"让语句更自然
            cuisine_str = ", ".join(self.cuisine_types[:-1]) + " and " + self.cuisine_types[-1]
            print(f"Our food menu specializes in {cuisine_str}")

调用示例

现在你可以传入任意数量的菜系了:

# 单个菜系的情况
restaurant_1 = Restaurant("See Food", "Soul Food")
restaurant_1.describe_restaurant()

# 多个菜系的情况
restaurant_2 = Restaurant("Global Bites", "Italian", "Japanese", "Mexican")
restaurant_2.describe_restaurant()

输出效果

运行上面的代码会得到:

The name of the restaurant is See Food
Our food menu specializes in Soul Food
The name of the restaurant is Global Bites
Our food menu specializes in Italian, Japanese and Mexican

这样不管餐厅有多少种菜系,都能清晰友好地展示出来啦!

备注:内容来源于stack exchange,提问作者Ifeoma Ogbodo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 13:23:06