【问题标题】:Store a list of strings in one attribute将字符串列表存储在一个属性中
【发布时间】:2020-07-02 14:17:24
【问题描述】:

我想我可能没有清楚地解释我的问题。我为此道歉。我会再试一次。

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

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


    【解决方案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')
    

    【讨论】:

    • 欢迎来到 StackOverflow。虽然此代码可能会回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将提高​​答案的长期价值。
    【解决方案2】:

    尝试使用以下代码:

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

    【讨论】:

      【解决方案3】:

      使用Arbitrary argument list。见this答案。

      例子:

      li = []
      def example(*arg):
          li = list(arg)
          print(li)
      
      example('string1', 'string2', 'string3')
      

      【讨论】:

        猜你喜欢
        • 2010-11-01
        • 1970-01-01
        • 2022-07-29
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多