pierre_allouez
pierre_allouez

Reputation: 23

How to sum attributes of all instances of an object

I want to sum the costsum attribute for all the instances of an object.

class ActivityCenter:

    def __init__(self, costpool, costsum, costdriver, cdunits):
        self.costpool = costpool
        self.costsum = costsum
        self.costdriver = costdriver
        self.cdunits = cdunits

cp1 = ActivityCenter("Material Handling", 480000, "Pounds", 160000)
cp2 = ActivityCenter("Production orders", 90000, "Num of POs", 200)

# I am looking to add up the costsum values for all instances, similar to:
costsumtotal = (cp1.__dict__.get("costsum")) + (cp2.__dict__.get("costsum"))

So far I've tried using sum() with comprehension as follows, referring to this solution:

B = []
for i in range(10):
    B.append(ActivityCenter())

s = sum(i.costsum for i in B)

But I am having trouble overcoming the TypeError that I'm missing 4 required positional arguments.

Upvotes: 1

Views: 5146

Answers (1)

Daewon Lee
Daewon Lee

Reputation: 630

To utilize sum built-in function in Python for member variables of objects, you need to make a sequence (e.g, tuple or list) of the member variables of the objects. The following snippet shows how to make a list of objects' member variables. The code you posted omits the comprehension expression. I hope it will be helpful :)

class ActivityCenter:

    def __init__(self, costpool, costsum, costdriver, cdunits):
        self.costpool = costpool
        self.costsum = costsum
        self.costdriver = costdriver
        self.cdunits = cdunits

"""
Create some objects

objs = []
for i in range(num_obj):
    objs.append(ActivityCenter(<some value>,<...>,<...>,<...>))

Or use objects to make a list
"""
cp1 = ActivityCenter("Material Handling", 480000, 160000, "Pounds")
cp2 = ActivityCenter("Production orders", 90000, 200, "Num of POs")
cp3 = ActivityCenter("Marketing", 120000, 1000, "Num of events")

objs = [cp1, cp2, cp3]

total_cost = sum([obj.costsum for obj in objs])  # List comprehension
print("Total cost: ", total_cost)

Upvotes: 5

Related Questions