accessing class attributes

Arnaud Delobelle arnodel at googlemail.com
Wed May 28 12:59:42 EDT 2008


eliben <eliben at gmail.com> writes:

> Hello,
>
> I have a game class, and the game has a state. Seeing that Python has
> no enumeration type, at first I used strings to represent states:
> "paused", "running", etc. But such a representation has many
> negatives, so I decided to look at the Enum implementation given here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
>
> So, I've defined:
>
> class Game:
>   self.GameState = Enum('running', 'paused', 'gameover')
>
>   def __init__
>    ... etc
>
> Later, each time I want to assign a variable some state, or check for
> the state, I must do:
>
>   if state == self.GameState.running:
>
> This is somewhat long and tiresome to type, outweighing the benefits
> of this method over simple strings.
>
> Is there any better way, to allow for faster access to this type, or
> do I always have to go all the way ? What do other Python programmers
> usually use for such "enumeration-obvious" types like state ?

Why not define GameState outside your Game class?

Then you can write:

    if state == GameState.running

which is slightly shorter.

Or you could do:

class Game:
    RUNNING, PAUSED, GAMEOVER = 0, 1, 2

and test like this:

    if state == Game.RUNNING

Or, I've just thought of this simple state class:

class State(object):
    def __init__(self, state):
        object.__setattr__(self, '_state', state)
    def __getattr__(self, attr):
        return attr == self._state
    def __setattr__(self, attr, val):
        object.__setattr__(self, '_state', attr)

>>> state = State('running')
>>> state.running
True
>>> state.paused
False
>>> state.paused = True
>>> state.paused
True
>>> state.running
False

So you could write:

    if state.running: ...

-- 
Arnaud




More information about the Python-list mailing list