I have a class to represent NFL quarterbacks. In each instance will be a list of dictionaries, where each entry contains information regarding the QB stats for the game played. I need to generate the average number of yards gained per game based on all quarterbacks in my DB. I could easily do this outside of the object oriented structure by just looping through my instances, building a list, etc... but I think there must be some elegant way to do this object oriented style. So I'd like to build this function "get_avg", I will pass it the name of the variable I want the average from, like "get_avg('pass_yards')" or "get_avg('pass_attempt')" and it should return an average based on every instance, and every game in each instance, in existence.
class qb:
def __init__(self, name, espn_player_id):
self.name = name
self.espn_player_id = espn_player_id
self.games=[]
def add_game(self, g):
self.games.append(g)
@classmethod
def get_avg(cls, var):
##create one list based on each game entry in each instance and return average
qb_data = s.query(Box_Score).filter(Box_Score.pass_attempt>8).all()
seen = set()
qbs = [qb(g.player_name, g.espn_player_id) for g in qb_data if g.espn_player_id not in seen and not seen.add(g.espn_player_id)]
for q in qbs:
for g in [qb_game for qb_game in qb_data if qb_game.espn_player_id==q.espn_player_id]:
q.add_game({"date": g.date, "pass_attempt": g.pass_attempt, "pass_made": g.pass_made, "q_team": g.team_name, "opp_team": "",
"pass_yards": g.pass_yards, "pass_td": g.pass_td, "pass_int": g.pass_int, "pass_longest": g.pass_longest})
print qb.get_avg('pass_attempt')
print qb.get_avg('pass_td')