如何从参数中添加2个输入?

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

我已经制作了这段代码,现在我想从“产品”类中添加价格。所以我有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', 'Daphne Kramer', 'Rotterdam')
customer2 = Customer('445412', 'Kim de Vries', '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
2个回答
0
投票

好像你想得到所有产品价格或订单总和的总和。两者都是相同的结果,但是您有两个包含相同信息的类,因此您可以通过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

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


0
投票

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

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

每当产品被添加到列表中时,将每个产品的价格添加到总数中 -

    def add1(self, product):
        self.product.append(product) 
        self.total += product.price
© www.soinside.com 2019 - 2024. All rights reserved.