[Tutor] About classes and databases

Alan Gauld alan.gauld at btinternet.com
Sun Nov 22 17:30:08 CET 2009


"Michele Alzetta" <michele.alzetta at gmail.com> wrote

> 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?

Same way you do any otrher kind of initialisation as arguments to the init 
method.
In fact you could create the atetime objects first and just pass them as a 
single value.
Or am I missing your point?

> 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?

You probably need to use a loop and a collection.
Either a list accessed via index or a dictionary using some set of key
values from the object(ID or Name etc)

> 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?

With 500 instances you are probably getting close to the point where a
database would be better. Its not impossible in memory but if you need to 
do
searches to select certain subsets etc then a database and SQL are probably
the way to go. OTOH if your problem is more about performing complex 
algorithms
using the objects them memory might be more suitable.

If you expect the problem to scale up much bigeger than 500 instances I'd
definitely go for a database.

> But is it possible to store datetime objects and dictionaries in a 
> database?

A data base table can be thought of as a dictionary.
Andmost databases have their own concept of a data object that does
most of what datetime does in Python.

If you go the database route you will need to consider the partitioning of
the application between pure python and SQL. Bulk operations should
be in SQL, operations on a single object could be on either and long 
running
calculations are probably best in Python.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list