On 13/06/14 19:20, diliup gabadamudalige wrote:
I declare the following dict at the beginning of the program.
KEY_SIGNATURES = {"C": [], "G": ["F"], "D": ["F", "C"], "A": ["F", "C",
"G"], "E": ["F", "C", "G", "D"], "B": ["F", "C", "G", "D", "A"], "F#":
now in the functions when ever I need to access i just use it.
eg:
sharps_or_flats = KEY_SIGNATURES[key]
or I can create it like this
class Variables():
def __init__(self, adv):
self.KEY_SIGNATURES = {"C": [], "G": ["F"],
now I call the class with
v=Variables()
now the same dict is
v.Key_SIGNATURES
my questions:
which is better to use and why?
As always there is no absolute answer. It depends on what you
are doing in a wider context.
However from your message you may be missing the point of the class
solution. The pointy of a class is to bring together the variables
*and the functions* that operate on those variables. So you should
not be doing v.Key_SIGNATURES from functions outside the class,
rather you should be defining your functions as methods of the
class and inside those methods using self.Key_SIGNATURES
Also a class called 'variables' is usually a bad design smell.
The class should be called something meaningful in the context
of your program. Something that represents the data and operations
that you have captured within it.
If you discover you have captured two unrelated concepts then
split the class into two. That will encourage reuse but also make
your code much more readable.
Do both remain in memory(separately of course) till I exit the program
once I run it? Will memory usage be the same?
For data this small what happens in memory should be the least of your
worries. Its much more important to get a design that is readable,
maintainable and reliable. Only when you have proved there is a
memory issue to solve do you need to start worrying about it.
will the creation of the dict take the same time in both above?
But if you are really worried about it use the timeit module or the
profiler to find out, don't guess or rely on others guesses.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor