For example, I'm working with musical notes, so I have a global
dictionary like this:
natural_notes = {'C': 0, 'D': 2, 'E': 4 ....}
This actually works fine. I was just thinking if it wasn't better to
use class variables.
Since I have a class Note, I could write:
class Note:
C = 0
D = 2
...
Which style maybe better? Are both bad practices?
Depends. Does your program use the note values as named constants, or
does it lookup the values dynamically based on the note name?
If the former, then the class is marginally better, though putting the
assignments in a (possibly separate) module would probably be best. If
the latter, than the dictionary is fine.
Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
It really depends on how you plan to use them. I might use a
dictionary if I'm likely be handling the notes as characters. If they
are just constants that I plan to use in my program, I would probably
just define a set of global names. The best practice I have found is a
combination.
NOTES = C,D,E,F,G,A,B = "CDEFGAB"
note_2_step = dict(C=0, D=2, E=4, F=5, G=7, A=9, B=11)
This allows you to do both. There are schemes where you might want to
use a class, but without more information it doesn't really seem
necessary. Globals are frowned upon, but constant tend to be just
fine.
Matt
I would *probably* find 'Note.C' more natural to use than
"natural_notes['C']".
Michael Foord
You can also put them in a module:
notes.py
========
C = 0
D = 2
....
Then you can:
import notes
print notes.F - notes.C
or
from notes import *
print F - C
If your application consists of several files this may be a good idea.
--
Arnaud