assigning values in __init__
Ben Finney
bignose+hates-spam at benfinney.id.au
Mon Nov 6 23:21:44 EST 2006
John Salerno <johnjsal at NOSPAMgmail.com> writes:
> 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?
A tuple is fine, but assumes that there is a logical *sequence* to
these values. If that's true, it should be no problem to assign them as:
class Character(object):
def __init__(self, name, stats):
self.name = name
(self.strength, self.dexterity,
self.intelligence, self.luck) = stats
>>> foo = Character("Foo", (10, 11, 9, 10))
>>> print foo.name, foo.strength, foo.intelligence
Foo 10 9
In this case, though, I don't see any value in a specific sequence, so
a mapping looks better to me and gives the caller more flexibility in
how to set it up.
class Character(object):
stat_keys = ['strength', 'dexterity', 'intelligence', 'luck']
def __init__(self, name, stats):
self.name = name
self.stats = {}
for (stat_key, stat_value) in [(k, stats[k])
for k in self.stat_keys]:
setattr(self, stat_key, stat_value)
>>> foo = Character("Foo", dict(
... dexterity = 11, luck = 10,
... strength = 10, intelligence = 9,
... ))
>>> print foo.name, foo.strength, foo.intelligence
Foo 10 9
> I'm trying to think ahead to when I might want to add new
> attributes
In which case you almost certainly want a mapping, not a sequence.
> and I want to make sure this doesn't get crazy with individual
> parameters instead of just the one list.
This is one of the many reasons why Python's built-in composite types
are so useful. A group of semantically-related values can be passed as
a single composite value.
--
\ "I hope that after I die, people will say of me: 'That guy sure |
`\ owed me a lot of money.'" -- Jack Handey |
_o__) |
Ben Finney
More information about the Python-list
mailing list