如何将一个参数的2个输入加在一起?

时间:2019-03-09 19:35:32

标签: python class definition

我已经编写了这段代码,现在我想从“产品”类中添加价格。因此,我有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()

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分: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

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