[Tutor] making a list of a custom object

Dave Angel davea at davea.name
Sat Sep 20 14:33:46 CEST 2014


Kate Reeher <madecunningly at outlook.com> Wrote in message:


> I have a custom class called Game, and it has a variable called "goals". I'd like
> to make this a list of custom objects, with various information about the goals.

> class Game:
> 	goals = {}

That's a class attribute; the others below are instance
 attributes. And it's a dict not a list. Perhaps you
 want
      goals = []

But more likely you're expecting to have more than one game, each
 with its own list of goals. In this case you'd want an
 initializer method, and within it you'd say 

         self.goals = []

You'd also want to instantiate at least one game, perhaps like
 (outside of the class definition)

game = Game ()
	
> class Goal(object):
> 	def __init__(self,time,goal_by,assist_by,team,is_powerplay ):
>			self.time=time
>			self.goal_by=goal_by
>			self.assist_by=assist_by
>			self.team=team
>			self.is_powerplay=is_powerplay

> This might be where you should append self to the class attrinute.


> Is that Goal class set up correctly? 

One of many possibilities. 

> For an instance of Game called game, is this how you'd set a 
> variable of a goal?
> game.goals[i].time= time 

First you have to create the goal.

my_goal = Goal (....)

Then you probably need to add that goal to a particular Game.

game.goals.append (my_goal)

Then if you have appended several, and you need to patch the time
 of a particular one (the ith one),  you might use your statement.
  But typically in a game, I'd figure the time for a particular
 goal wouldn't change. 




-- 
DaveA



More information about the Tutor mailing list