将字符串列表存储在一个属性中

问题描述 投票:0回答:4

我想我可能没有清楚地解释我的问题。我对此表示歉意。我会再试一次。

我有一个具有某些属性的父类:

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中的风味列表:

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

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

如果我使用 concat,我会收到消息说名称未定义。

我很抱歉第一次没有正确解释问题,并感谢所有的帮助。

python python-3.x class attributes
4个回答
1
投票
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')

0
投票

尝试使用以下代码:

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

0
投票

使用任意参数列表。请参阅这个答案。

示例:

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

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

-2
投票

据我所知,你正在做《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()
© www.soinside.com 2019 - 2024. All rights reserved.