Google Grupper støtter ikke lenger nye Usenet-innlegg eller -abonnementer. Historisk innhold er fortsatt synlig.

Global dictionary or class variables

Sett 1 gang
Hopp til første uleste melding

Mr.SpOOn

ulest,
24. okt. 2008, 16:44:3824.10.2008
til pytho...@python.org
Hi,
in an application I have to use some variables with fixed valuse.

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?

Chris Rebert

ulest,
24. okt. 2008, 18:17:0124.10.2008
til Mr. SpOOn, pytho...@python.org

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

> --
> http://mail.python.org/mailman/listinfo/python-list
>

Matimus

ulest,
24. okt. 2008, 19:53:5524.10.2008
til

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

Meldingen er slettet

Fuzzyman

ulest,
25. okt. 2008, 07:56:0925.10.2008
til

I would *probably* find 'Note.C' more natural to use than
"natural_notes['C']".

Michael Foord

--
http://www.ironpythoninaction.com/

Arnaud Delobelle

ulest,
26. okt. 2008, 09:06:1526.10.2008
til

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

0 nye meldinger