assigning values in __init__

Larry Bates larry.bates at websafe.com
Mon Nov 6 23:10:20 CET 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.

Sounds like what you should be doing is something like keyword arguments
instead.

class Character(object):
    def __init__(self, name, **kwargs):
        self.name=name
        for key, value in kwargs.items():
            setattr(self, key, value)


z=Character('name', strength=10, dexterity=5, intelligence=3, luck=0)

Now you can easily introduce new keyword arguments.

-Larry



More information about the Python-list mailing list