assigning values in __init__

Gerard Flanagan grflanagan at yahoo.co.uk
Mon Nov 6 23:10:54 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?
>

How about:

class Character(object):

    def __init__(self, name, **kwargs):
        self.name = name
        self.__dict__.update(kwargs)

c = Character( "Plato", strength=10, luck=12)

print getattr(c, "strength")
print getattr(c, "luck")

10
12




More information about the Python-list mailing list