Home > other >  How to sum one of the parameters of all objects that belong to same class
How to sum one of the parameters of all objects that belong to same class

Time:09-17

class Bill:

    def __init__(self,type,amount):
        self.amount = amount
        self.type = type

    def total(*args):
        total_bill = []
        for arg in args:
            total_bill.append(arg.amount)
        return sum(total_bill)

b1 = Bill('Elect',500)
b2 = Bill('Gas',300)
b3 = Bill('Other',100)

print(Bill.total(b1,b2,b3))

print(b1.total(b2))

I am trying to understand Python OOP logic. Here, I created a method (total) that calculates total amount of the bill objects. The code works, but it seems very unusual, as the second print (b1.total(b2)) is non-sense (when I call it as a method of a instance). Hence, I wonder if that would be a decent way? I mean create a method for the calculations between the instance inside of class? What would be the best way to get sum of the bills. (The number of bills could be much higher.)

CodePudding user response:

You can use a class variable to hold all the bill items, then use that when calculating the total rather than passing the items as arguments.

class Bill:

    all_bills = []

    def __init__(self,type,amount):
        self.amount = amount
        self.type = type
        self.all_bills.append(self)

    @classmethod
    def total(cls):
        return sum(arg.amount for arg in cls.all_bills)

b1 = Bill('Elect',500)
b2 = Bill('Gas',300)
b3 = Bill('Other',100)

print(Bill.total())        
  • Related