gpt4 book ai didi

Python Class with Arbitrary number of Attributes(具有任意数量属性的Python类)

转载 作者:bug小助手 更新时间:2023-10-25 15:47:26 25 4
gpt4 key购买 nike



I have this exercise that I worked on and it worked perfectly. This is it:

我有一个我做过的练习,它效果很好。就是这样:


class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant():
print("The name of the restaurant is " + self.restaurant_name)
print("Our food menu specializes in " + self.cuisine_type)

restaurant_1 = Restaurant("See Food", "Soul Food")
restaurant_1.describe_restaurant()

But, what if the restaurant serves different cuisine types. How do I go about it?

但是,如果这家餐厅提供不同类型的菜肴怎么办?我该怎么做呢?


I know I can make the cuisine_type attribute collect an arbitrary number of arguments using (*). But how do I output it in the describe_restaurant() method?

我知道我可以使用(*)让CUISINE_TYPE属性收集任意数量的参数。但是如何在Describe_Restaurant()方法中输出它呢?


更多回答

For some reason, the main code is not indenting. Please bear with me..

由于某些原因,主代码没有缩进。请容忍我..

Could you supply a list of strings for cuisine_type? eg restaurant_1 = Restaurant("See Food", ["Soul Food", "Tapas", "Chinese"])

您能提供CUISINE_TYPE的字符串列表吗?例如Restaurant_1=Restaurant(“See Food”,[“Soul Food”,“Tapas”,“Chinese”])

Your code has self missing in def describe_restaurant(self):. Corrected in my answer below.

您的代码在def describe_restaurant(self):中缺少self。在我下面的回答中更正。

优秀答案推荐

You could use code along the lines of:

你可以使用代码如下:


class Restaurant():
def __init__(self, restaurant_name, *cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("The name of the restaurant is " + self.restaurant_name)
txt = ' and '.join(self.cuisine_type)
print("Our food menu specializes in " + txt)

restaurant_1 = Restaurant("See Food", "Soul Food", "Vegan")
restaurant_1.describe_restaurant()

prints

指纹


The name of the restaurant is See Food
Our food menu specializes in Soul Food and Vegan

alternatively to access the individual types you could use within the method code:

或者,要访问您可以在方法代码中使用的各个类型:


for food in self.cuisine_type:
print(food)

更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com