accessing class attributes

giltay at gmail.com giltay at gmail.com
Wed May 28 15:25:21 EDT 2008


On May 28, 12:09 pm, eliben <eli... at gmail.com> wrote:
> 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
[...]
> 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 ?

I tend to use string constants defined at the module level, e.g.:

##----- in jobclass.py:
# Status indicators
IDLE = 'IDLE'
RUNNING = 'RUNNING'
FINISHED = 'FINISHED'

class Job(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.status = IDLE

    def run(self):
        self.status = RUNNING
        self.do_work()
        self.status = FINISHED
[...]
##----- in another module
job = jobclass.Job()
job.start()
while job.status == jobclass.RUNNING:
    print 'Job is running.'
    time.sleep(SLEEP_SECONDS)
##-----

I've also used dummy objects, eg:

##-----
class RunStatus:
    pass


IDLE = RunStatus()
RUNNING = RunStatus()
FINISHED = RunStatus()
##-----

I've had lots of success with these two methods.  If you think an
enumeration is the most appropriate way, then:

##-----
RunStatuses = Enum('idle', 'running', 'finished')
IDLE = RunStatuses.idle
RUNNING = RunStatuses.running
FINISHED = RunStatuses.finished
##-----

I figure if you're only going to have a few dozen enumeration values,
then don't worry about cluttering up the module namespace with
variable names for constants.

Geoff G-T



More information about the Python-list mailing list