[Tutor] About classes and databases

Dave Angel davea at ieee.org
Sun Nov 22 13:05:56 CET 2009


Michele Alzetta wrote:
> Hallo all!
>
> Long time since I last dabbled in python :-(
>
> I was thinking of a possible solution to a problem I have: I could make a
> Class which contains, amongst other things, a couple of datetime.datetime
> objects.
> The class also will have to contain an element taken from a Tuple and
> various elements taken from a series of dictionaries.
>
> First problem: when creating each instance of the class I have to pass it
> the information necessary to create the correct datetime objects - how would
> I do this?
> Second problem: I would find myself to be working with something in the
> order of 500 instances of this class contemporaneously, how do I create them
> "automatically" from a series of data and once I've created them how do I
> grab the correct one when I need it?
>
> Or do you think my approach is all wrong, and it would be better for me not
> to use classes at all and to store the data in a database?
> But is it possible to store datetime objects and dictionaries in a database?
>
> Thanks for any comments.
>
> Michele
>
>   
You don't supply enough information to get more than generic answers.  
And your wording is confusing to me as well. It reminds me of the kind 
of homework assignment that goes:   

Question: Use "confused" in a sentence. 
Response:  "I can't figure out a way to use "confused" in a sentence, so 
I wrote this"

It's not at all clear whether there will be a tuple and some 
dictionaries for each instance, or whether these are to be collection 
objects that your class' constructor will consult.

Problem 1:   Lots of ways to create a datetime object.  Which one you 
should use depends on what information you're starting with.  For 
example, if you're starting with text you probably want strptime(), 
while if you have a timestamp, you might use utcfromtimestamp().

Problem 2:  500 instances isn't that many, unless the object is very 
complex.  So keeping them in memory is quite practical.  But you have to 
decide the type of container, and that depends mainly on how you plan to 
access them.  Built-in choices are a list and a dict.  Dict is quite 
useful if you're always going to find them based on a single type of 
key, and if that key is unique.

But suppose these objects represent people, and you sometimes have to 
find a particular one based on name, and sometimes based on age, and 
...   Then a single dictionary doesn't work well for more than the one case.

The other tradeoff that needs to be made is whether the collection gets 
changed dynamically, or just gets built once.  And whether it needs to 
persist through multiple runs of the program.  And whether building it 
takes a long time.  And how often the collection will be accessed by a 
single (primary) key, versus multiple ones.  And so on.




More information about the Tutor mailing list