【问题标题】:How to create multiple objects using a class, where the objects' attributes are inserted by the user?如何使用类创建多个对象,其中对象的属性由用户插入?
【发布时间】:2022-01-04 16:49:02
【问题描述】:

我想我已经掌握了基本概念,但我无法真正让它正常工作。我想创建 5 个具有自己属性的不同对象,每个对象 3 个,但它们必须是输入。它们必须使用另一个函数创建,然后返回它们以显示用户并将它们放入列表中。这就是我所拥有的,但我不知道如何使它工作:


class SmartPhone:
    def __init__(self, manufacturer, model, cost):
        self.manufacturer = manufacturer
        self.model = model
        self.cost = cost


manufacturer = input("Εισήγαγε τον κατασευαστή: ")
model = input("Εισήγαγε το μοντέλο: ")
cost = input("Εισήγαγε την λιανική τιμή: ")


def smart_phones(manufacturer, model, cost):
    smartPhones = []
    phone = SmartPhone(manufacturer, model, cost)
    smartPhones.append(phone)
    return "Smartphone: " + str(phone), smartPhones


smart_phones = smart_phones(manufacturer, model, cost)
for i in range(0, 5):
    print(smart_phones)

问题基本上在于 smart_phones 功能。

【问题讨论】:

  • 请注意,您正在用它返回的元组覆盖函数smart_phones

标签: python class


【解决方案1】:

不确定我是否完全理解您的描述,但我会尽力提供帮助。

如果您尝试获取 5 个不同的 SmartPhone 对象,则需要向用户询问 15 个输入(每个不同的手机 3 个)。在您的代码中,您似乎只询问了 3 个字段一次。您实际上是在打印相同的对象(具有相同的 3 个字段)5 次。

试试这样的:

class SmartPhone:
    def __init__(self, manufacturer, model, cost):
        self.manufacturer = manufacturer
        self.model = model
        self.cost = cost

smartPhones = []

def smart_phones(manufacturer, model, cost):
    phone = SmartPhone(manufacturer, model, cost)
    smartPhones.append(phone)
    return "Smartphone: " + str(phone), smartPhones

for i in range(0, 5):
    smart_phones(input("Εισήγαγε τον κατασευαστή: "),input("Εισήγαγε το μοντέλο: "),input("Εισήγαγε την λιανική τιμή: "))
    
for i in range(1, 6):
    print("Phone " + str(i))
    print("Manufacturer: " + smartPhones[i].manufacturer + " ")
    print("model: " + smartPhones[i].model + " ")
    print("cost: " + smartPhones[i].cost + "\n")

基本上,您可以输入每部手机所需的每 3 个值。 而不是打印内存中对象的位置,而是打印每个循环中的每个值。

【讨论】:

    【解决方案2】:

    您正在列表中附加 SmartPhone 类的对象。这就是为什么 print() 会返回内存中对象的地址。也许您想附加制造商、型号、成本的列表。像这样的:

    def smart_phones(manufacturer, model, cost):
       smartPhones = []
       phone = SmartPhone(manufacturer, model, cost)
       smartPhones.append([phone.manufacturer,phone.model,phone.cost])
       return "Smartphone: " +  str(smartPhones)
    

    此外,您只能获得一次输入。要创建 5 个对象,请执行以下操作:

    for i in range(0, 5):
       manufacturer = input("Creator:")
       model = input("Models:")
       cost = input("Cost:")
       print(smart_phones(manufacturer, model, cost))
    

    【讨论】:

      【解决方案3】:

      如果要创建SmartPhone 对象,类方法是封装必要I/O 的好地方。

      class SmartPhone:
          def __init__(self, manufacturer, model, cost):
              self.manufacturer = manufacturer
              self.model = model
              self.cost = cost
      
          @classmethod
          def from_user(cls):
              manufacturer = input("Εισήγαγε τον κατασευαστή: ")
              model = input("Εισήγαγε το μοντέλο: ")
              cost = input("Εισήγαγε την λιανική τιμή: ")
              return cls(manufacturer, model, cost)
      
      
      smart_phones = [SmartPhone.from_user() for _ in range(5)]
      

      【讨论】:

        【解决方案4】:

        要以易于理解的方式打印对象,您需要定义 __repr____str__ 方法。

        一个简单的例子:

        class SmartPhone:
            def __init__(self, manufacturer, model, cost):
                self.manufacturer = manufacturer
                self.model = model
                self.cost = cost
                
            def __repr__(self):
                return f"A ${self.cost} {self.__class__.__name__}: {self.manufacturer} {self.model}"
        

        定义几个例子:

        x=SmartPhone('Apple', '13', 1200)    
        y=SmartPhone('Samsung', 'Galaxy', 900) 
        

        然后列出这些:

        li=[x,y]
        

        那你就可以随意打印了:

        >>> print(li)
        [A $1200 SmartPhone: Apple 13, A $900 SmartPhone: Samsung Galaxy]
        
        >>> x
        A $1200 SmartPhone: Apple 13
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-03
          • 2014-07-28
          • 1970-01-01
          • 2017-08-11
          • 2020-03-05
          • 2020-09-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多