python-3.x 将字符串列表存储在一个属性中

368yc8dk  于 2023-01-22  发布在  Python
关注(0)|答案(4)|浏览(131)

我想我可能没有解释清楚我的问题。我为此道歉。我会再试一次。
我有一个具有某些属性的父类:

class Restaurant():
'This is the restaurant class'

def __init__(self, name, cuisine_type):
    self.name = name
    self.cuisine_type = cuisine_type

然后我有一个子类继承父类的所有属性并添加一个新属性:

class IceCreamStand():

def __init__(self, *flavor):
    'Attributes of parent class initialised'
    self.flavor = flavor

现在我尝试打印一个存储在属性flavor中的flavour列表:

def desc_flavor(self):
    print('This Ice_Cream shop has ' + self.flavor + ' flavors')

flavor1 = IceCreamStand('Mango', 'Raspberry', 'Coffee', 'Vanilla')

如果我使用concat,我会得到一条消息,说名称没有定义。
我为第一次没有正确解释问题而道歉,并感谢所有的帮助。

qf9go6mv

qf9go6mv1#

class IceCreamStand(Restaurant):
      def __init__(self,restaurant_name, cuisine_type):
          super().__init__(restaurant_name, cuisine_type)
         
      def describe_flavors(self,*flavors):
          print(f'{self.restaurant_name} has the following flavors:')
          for self.flavor in flavors:
              print(f'-{self.flavor}')
           
restaurant =IceCreamStand('DQ','ice cream')
restaurant.describe_restaurant()
restaurant.describe_flavors('Chocolate','Mango', 'Raspberry', 'Coffee', 'Vanilla')
plupiseo

plupiseo2#

请尝试使用以下代码:

def __init__(self, *attribute1):
    self.atributte1 = attribute1
qni6mghb

qni6mghb3#

使用任意参数列表。参见this答案。
示例:

li = []
def example(*arg):
    li = list(arg)
    print(li)

example('string1', 'string2', 'string3')
flvtvl50

flvtvl504#

据我所知,你正在做Python速成课程第9章的练习,这是我在另一个练习中做的代码,希望对你有帮助。

class Restaurant():
"""A simple attempt to model a restaurant."""

    def __init__(self, restaurant_name, cusisine_type):
        self.name = restaurant_name
        self.type = cusisine_type

    def describe_restaurant(self):
        print("Restaurant name is " + self.name.title() + ".")
        # print(self.name.title() + " is a " + self.type + " type restaurant.")

    def open_restaurant(self):
        print(self.name.title() + " is open!")

class IceCreamStand(Restaurant):
"""Making a class that inherits from Restaurant parent class."""

    def __init__(self, restaurant_name, cusisine_type):
        super().__init__(restaurant_name, cusisine_type)
        self.flavor = 'chocolate'

    def display_flavors(self):
        print("This icrecream shop has " + self.flavor + " flavor.")

# create an instance of IceCreamStand
falvors = IceCreamStand('baskin robbins', 'icecream')

# print("My restaurant name is: " + falvors.name)
# print("Restaurant is which type: " + falvors.type)
falvors.describe_restaurant()
falvors.open_restaurant()

# Calling this method
falvors.display_flavors()

相关问题