Python Forum
How do I sum instance attributes?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I sum instance attributes?
#1
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)
Reply
#2
Do you have the code of the Player class?
Reply
#3
class Player:

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


        self.player = player
        self.pos = pos
        self.salary = salary
        self.age = age
Reply
#4
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)
Reply
#5
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.
Reply
#6
(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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
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?
Reply
#8
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)
Reply
#9
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)
Reply
#10
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to add class instance attributes from list 999masks 2 2,701 Jul-22-2019, 07:59 AM
Last Post: 999masks
  Class object instance. Link instance attribute to class. Can it be done easier. Windspar 7 4,145 Dec-03-2018, 11:16 PM
Last Post: Windspar
  How to check if class instance exists in a list of class instance objects? sonicblind 23 20,277 May-27-2018, 05:44 AM
Last Post: buran
  Newbie here - how do i compare\check 2 attributes of an instance BenSalem 2 3,199 Aug-01-2017, 02:42 PM
Last Post: ichabod801
  Python3x running only with one instance (how can I prevent too many running instance) harun2525 5 18,216 Jul-21-2017, 07:36 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020