Two questions about style and some simple math

J Kenneth King james at agentultra.com
Tue Jan 20 10:26:33 EST 2009


Spoofy <spoofy1 at gmx.net> writes:

> .. <snip> ..
>
> 2.
>
> For maintaining the character attributes I creates a seperate class. I
> wonder weather this is an "overuse" of OO (instead of just making the
> attributes plain variables of the Char class) and if the way I wrote
> this is OK (somehow this looks cool to me but maybe too "showy"?)
>
> class Attributes(object):
>     ATTRIBUTES = {"attack": 0, "defence": 0, "ability": 0, "courage":
> 0, "condition": 0}
>     def __init__(self, **kwargs):
>         self.__dict__.update(self.ATTRIBUTES)
>         for arg in kwargs:
>             if arg not in self.ATTRIBUTES:
>                 raise ValueError("Unkown character attribute '%s'" %
> arg)
>             self.__dict__[arg] = kwargs[arg]
>
>
> Again, I appreciate any tips. I you need more code (for the bigger
> picture or such), just ask.
>
> Thanks in advance

I think the first part has been covered well.

If you want an opinion, this class isn't "showy" at all, rather it is
ugly and unnecessary.

Firstly it's bad because:

1. ATTRIBUTES is still modifiable after insantiation. This breaks the
restriction you're expressing in __init__

2. You want to avoid modifying __dict__ directly if you can. It bypasses
the whole point of using named attributes.

What you'd really want in a case where a class has a restricted set of
attributes is __slots__. Classes defined with it have no __dict__ and
thus attributes cannot be dynamically added to them after
instanciation (a __slots__ defined class will raise an exception in this
case).

However, even in this case, it doesn't make sense to encapsulate the
attributes of your game's Character objects in this way. Your "Hero"
class should have its attributes directly associated to it: Hero.health,
Hero.defence, and so forth. If you want to encapsulate a common set of
attributes available to a "class" of objects, you'd create a "Character"
class with those general attributes, sub-class your NPC's and Hero from
it, and specialize those sub-classes as needed.

HTH,

j_king



More information about the Python-list mailing list