assigning values in __init__

Steve Holden steve at holdenweb.com
Mon Nov 6 21:19:20 EST 2006


John Salerno wrote:
> Let's say I'm making a game and I have this base class:
> 
> class Character(object):
> 
>      def __init__(self, name, stats):
>          self.name = name
>          self.strength = stats[0]
>          self.dexterity = stats[1]
>          self.intelligence = stats[2]
>          self.luck = stats[3]
> 
> Is this a good way to assign the values to the different attributes? 
> Should 'stats' be a list/tuple (like this), or should I do *stats instead?
> 
> I'm trying to think ahead to when I might want to add new attributes, 
> and I want to make sure this doesn't get crazy with individual 
> parameters instead of just the one list.
> 
> Or maybe there's some way to loop through two lists (the stats and the 
> attributes) and assign them that way? I was thinking of a nested for 
> statement but that didn't seem to work.

If your program deals with 4-element tuples then although you *could* 
use *stats in your calls to pass each element of the tuple as a single 
argument, that's not really necessary. A way to write the 
initializations you want without using indexing is:

class Character(object):

      def __init__(self, name, stats):
          self.name = name
          self.strength, self.dexterity, \
          self.intelligence, self.luck = stats

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list