首页 文章

在python OOP中如何打印具有属性的对象列表,并添加每个产品的总价格

提问于
浏览
1

我是一个非常擅长python和OOP的人,我想打印一个包含3个属性的3个对象的列表,其中一个属性是价格,我想最终这三个价格加起来给我总钱这花费了3个产品 . 这是我的代码:

from products import PhysicalProduct

class Checkout:
    def get_total(self, product_list):
        total = 0
        for product in product_list:
            total += product.price
        return total

        def print_list(self, product_list):
            #print products with sku, price and the total

            pass


checkout = Checkout()
product_list = [
    #The properties are: "name", "sku", price
    PhysicalProduct("television", "100", 100),
    PhysicalProduct("radio", "101", 80),
    PhysicalProduct("computer", "105", 1080),
]
print(checkout.get_total(product_list))

It should look something like this:
电视:sku:100价格:100
收音机:sku:101价格:80
电脑:sku:105价格1080
总数:1260

3 回答

  • 1

    使用以下 print_list 方法声明:

    def print_list(self, product_list):
        for product in product_list:
            print(product.name, 'sku: {:0} price: {:1}'.format(product.sku, product.price))
        print('total:', self.get_total(product_list))
    
  • 1

    应该不难 . 你甚至可能不需要第二个功能,但如果你想拥有它,那么你可以这样做:

    class Checkout:
        def get_total(self, product_list):
            total = 0
            for product in product_list:
                total += product.price
            return total
    
        def print_list(self, product_list, total):
            #print products with sku, price and the total
            for item in product_list:
                print(item.name + ": sku: " + item.sku + " price: " + str(item.price), end="")
            print()
            print("total: " + str(total))
    
    checkout = Checkout()
    product_list = [
        #The properties are: "name", "sku", price
        PhysicalProduct("television", "100", 100),
        PhysicalProduct("radio", "101", 80),
        PhysicalProduct("computer", "105", 1080),
    ]
    total = checkout.get_total(product_list)
    checkout.print_list(product_list, total)
    
  • 1

    试试这个:

    for product in product_list:
        print(product.name +': sku: '+product.sku+' price: '+product.price)
    print('total: ' + str(checkout.get_total(product_list)))
    

    这应该做的要求

相关问题