Python Forum

Full Version: How do I sum instance attributes?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Say I have a bunch of instances of a class and one of the attributes below is the salary for every player. How would I calculate the sum of the salary for all players every time an instance is created?

Player1 = Player('John Smith','RB',749912,23)
Player2 = Player('Ron Ward', 'TE', 7000000, 26)
Player3 = Player('Matt Abrams','QB', 27525000, 30)
Player4 = Player('Anthony Atlee', 'LT', 11050000, 30)
Do you have the code of the Player class?
class Player:

 def __init__(self,player,pos,salary,age):


        self.player = player
        self.pos = pos
        self.salary = salary
        self.age = age
A general rule is that you need to worry about your code when the names of the variables contain a varying index such as Player1 Player2 Player3 etc. This is bad design. In such a case, the correct solution is to use a collection of instances such as a list
players = []
players.append(Player('John Smith','RB',749912,23))
players.append(Player('Ron Ward', 'TE', 7000000, 26))
...
With such a collection, it is easy to sum the salaries
result = sum(p.salary for p in players)
Thanks I appreciate it! Is there an easier way to to put the instances in a list without having to append each instance one at a time? I have a lot of instances of this class.
(Jul-17-2019, 01:23 AM)pythonprogrammer Wrote: [ -> ]Thanks I appreciate it! Is there an easier way to to put the instances in a list without having to append each instance one at a time? I have a lot of instances of this class.

How these 'lot of instances' are created? They don't automagically come to an existence.
class Player:
 
 def __init__(self,player,pos,salary,age):
 
 
        self.player = player
        self.pos = pos
        self.salary = salary
        self.age = age

Player1 = Player('John Smith','RB',749912,23)
Player2 = Player('Ron Ward', 'TE', 7000000, 26)
Player3 = Player('Matt Abrams','QB', 27525000, 30)
Player4 = Player('Anthony Atlee', 'LT', 11050000, 30)


players = []
players.append(Player('John Smith','RB',749912,23))
players.append(Player('Ron Ward', 'TE', 7000000, 26))
players.append(Player('Matt Abrams','QB', 27525000, 30))
players.append(Player('Anthony Atlee', 'LT', 11050000, 30))

result = sum(p.salary for p in players)
What I am saying is if I had 20 different instances of different players what would be the quickest way to compute the sum of the total salary of all players? As you see above I created an empty list called players and then appended each instance to it and used this formula to calculate the sum: result = sum(p.salary for p in players). Surely there is a quicker way to do it than to append all 20 instances to an empty list one at a time?
In the code above each player is created twice, you only need create them once and rather then appending, directly create the list of players.
class Player:

    def __init__(self, player, pos, salary, age):

        self.player = player
        self.pos = pos
        self.salary = salary
        self.age = age


players = [Player('John Smith', 'RB', 749912, 23),
           Player('Ron Ward', 'TE', 7000000, 26),
           Player('Matt Abrams', 'QB', 27525000, 30),
           Player('Anthony Atlee', 'LT', 11050000, 30)]


result = sum(p.salary for p in players)
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)
Just an observation: if there are two players named 'John Smith'? How to make distinction between them? With sum of salaries it is not a problem but if you want to query specific players data it might be.