【问题标题】:How do you add 2 inputs from an argument together?如何将一个参数的 2 个输入加在一起?
【发布时间】:2019-07-31 13:08:22
【问题描述】:

我已经编写了这段代码,现在我想从“产品”类中添加价格。所以我有2个产品:电脑和任天堂,我想把价格加在一起,我可以给这个定义一个,这样从产品3和4就可以加起来吗? 我希望我的问题有意义,我是编程初学者。

class Customer:
    def __init__(self, ID, name, address):
        self.ID = ID
        self.name = name
        self.address = address
    

    def customer_information(self):
        print('ID: '+ self.ID + ', Name: ' + self.name + ', Address: '+ self.address)

class Product:
    def __init__(self, product_name, product_ID, price):
        self.product_name = product_name
        self.product_ID = product_ID
        self.price = price

    def product_information(self):
        print(self.product_name+', '+self.product_ID + ', €'+str(self.price))

class Order:
    def __init__(self):
        self.customer = []
        self.product = []

    def add1(self, product):
        self.product.append(product)

    def customer_data(self, customer):
        self.customer.append(customer)
    

    def show(self):
        for c in self.customer:
            c.customer_information()
        print('This order contains:')
        for p in self.product:
            p.product_information()

customer1 = Customer('542541', 'Name', 'Rotterdam')
customer2 = Customer('445412', 'Name', 'Schiedam')
        
product1 = Product('Computer', '34456', 200.00)
product2 = Product('Nintendo', '12345', 14.99)
product3 = Product('Camera', '51254', 50.00)
product4 = Product('Go-pro', '51251', 215.00)


myOrder = Order()
myOrder.customer_data(customer1)
myOrder.add1(product1)
myOrder.add1(product2)


myOrder1 = Order()
myOrder1.customer_data(customer2)
myOrder1.add1(product3)
myOrder1.add1(product4)

myOrder.show()
myOrder1.show()

【问题讨论】:

  • 抱歉,您的问题没有意义。当您说“定义”时,您指的是什么种类的定义?函数定义?类定义?我也不明白你想让这个未指定的定义做什么。它的输入是什么,预期的输出或结果是什么?

标签: python class definition


【解决方案1】:

是的,您可以按类顺序创建另一个变量-

    def __init__(self):
        self.customer = []
        self.product = []
        self.total = 0

并在将产品添加到列表时将每个产品的价格添加到总价中-

    def add1(self, product):
        self.product.append(product) 
        self.total += product.price

【讨论】:

    【解决方案2】:

    您似乎想获得所有产品价格的总和,或订单总额。两者的结果相同,但是您有两个包含相同信息的类,因此您可以通过ProductOrder 计算总和:

    productsum = product1.price + product2.price + product3.price + product4.price
    ordersum = sum([p.price for p in myOrder.product]) + sum([p.price for p in myOrder1.product])
    
    
    print(productsum) # 479.99
    print(ordersum)   # 479.99
    

    无论哪种方式,您都会得到相同的答案,只需选择您想要的实现方式即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      相关资源
      最近更新 更多