Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python OOP中,如何打印具有属性的对象列表并添加每个产品的总价格_Python_Oop - Fatal编程技术网

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

在python OOP中,如何打印具有属性的对象列表并添加每个产品的总价格,python,oop,Python,Oop,我是python和OOP的行乞者,我想打印一个3个对象的列表,每个对象有3个属性,其中一个属性是价格,我想最后这三个价格加起来,给我3个产品的总成本。 这是我的密码: from products import PhysicalProduct class Checkout: def get_total(self, product_list): total = 0 for product in product_list: to

我是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))
它应该是这样的:
电视:sku:100价格:100
收音机:sku:101价格:80
计算机:sku:105价格1080

总数:1260应该不难。您甚至可能不需要第二个函数,但如果您想拥有它,则可以执行以下操作:

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)

使用以下
打印列表
方法声明:

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))
试试这个:

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

这应该符合要求

这里有问题吗?显示最终结果的外观