473,287 Members | 1,555 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

accessing class attributes

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/Coo.../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 ?

Thanks in advance
Eli
Jun 27 '08 #1
5 1552
eliben 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/Coo.../Recipe/413486

So, I've defined:

class Game:
self.GameState = Enum('running', 'paused', 'gameover')
That can't be what you've got. But I think I can guess what you meant
to show here.)
def __init__
... etc
Several options:

Define the Enum outside the class:
GameState = Enum('running', 'paused', 'gameover')
then later
class Game:
...
if state == GameState.running:
...
Or just simply define some values
RUNNING = 0
PAUSED = 1
GAMEOVER = 2
then later:
class Game:
...
if state == RUNNING:
...
Or try this shortcut (for the exact same effect):
RUNNING, PAUSED, GAMEOVER = range(3)

Gary Herron

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 ?

Thanks in advance
Eli
--
http://mail.python.org/mailman/listinfo/python-list
Jun 27 '08 #2
eliben <el****@gmail.comwrites:
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/Coo.../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

Jun 27 '08 #3
On May 28, 12:09 pm, eliben <eli...@gmail.comwrote:
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/Coo.../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
Jun 27 '08 #4
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/Coo.../Recipe/413486

I frequently use strings in place of enumeration in python. I have
found it to be very useful. I'm curious about the _many negatives_ you
have found?

For example, I wrote a module and one of the parameters to a function
was `mode`. Two of the modes were ALL_MODE and ONE_MODE.

At first I enumerated the modes:

MODES = ALL_MODE, ONE_MODE = 0, 1

And code using the mode tended to look something like this:

from package import module
module.foo(mode=module.ALL_MODE)

Of course, the following would also work, but isn't self descriptive:

module.foo(mode=0)

Then, after some user feedback I changed it to this:

MODES = ALL_MODE, ONE_MODE = "all one".split()

This maintained backwards compatabilty, but users could use the much
more concise (but still readable) version:

module.foo(mode="all")

Since then, I have adopted using strings in place of enum types as a
best practice.

Matt
Jun 27 '08 #5
On May 29, 3:08 am, Matimus <mccre...@gmail.comwrote:
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/Coo.../Recipe/413486

I frequently use strings in place of enumeration in python. I have
found it to be very useful. I'm curious about the _many negatives_ you
have found?

For example, I wrote a module and one of the parameters to a function
was `mode`. Two of the modes were ALL_MODE and ONE_MODE.

At first I enumerated the modes:

MODES = ALL_MODE, ONE_MODE = 0, 1

And code using the mode tended to look something like this:

from package import module
module.foo(mode=module.ALL_MODE)

Of course, the following would also work, but isn't self descriptive:

module.foo(mode=0)

Then, after some user feedback I changed it to this:

MODES = ALL_MODE, ONE_MODE = "all one".split()

This maintained backwards compatabilty, but users could use the much
more concise (but still readable) version:

module.foo(mode="all")

Since then, I have adopted using strings in place of enum types as a
best practice.

Matt
The problem with naming strings explicitly has to do with type safety.
If you make a mistake in a parameter's name, it won't be detected by
the interpreter and you can run into weird errors later. The other
problem is that all the possible options are not documented in one
convenient place, but you solved it by using a mixed approach of
uppercase "constants" having the values of strings.

Eli
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: JM | last post by:
Hello everyone, Does anybody know about, have documentation on, or have any code samples on how to access class members from a python class in C++. Say I have a simple python script: ...
3
by: joealey2003 | last post by:
Hi all... I included a css file on my html and i need to check some properties. The html is: <style id="myid" src="mycsspage.css"> </style> Now i need something to access it like: ...
2
by: damonf | last post by:
I'm currently trying to add an ASP hyperlink to a template column in a datagrid. The normal hyperlink column doesn't give me the ability to add attributes to the item. In my grid there are four...
3
by: Beorne | last post by:
In the classes I develop my attributes are always private and are exposed using properties. directly or to access the attributes using the properties? Does "wrapper" setter/getter properties...
2
Rafael Justo
by: Rafael Justo | last post by:
Hi, I'm new in python development (NEWBIE). While I was using Cheetah Templates I got a problem about accessing template variables. I have an object like this (class Template): >>> class...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.