[Tutor] Saving class instances

Alan Gauld alan.gauld at btinternet.com
Mon Jul 13 19:30:32 CEST 2009


"Thomas Scrace" <t.scrace at gmail.com> wrote

> class with attributes like name, artist, year etc.  However, I am at a  
> loss as to how to save these instances so that they can be retrieved  
> the next time I run the program.  I assume I need to write them to a  
> file somehow, 

That's one way and you can find an example and some advice 
on how to handle subclassing in the OOP topic of my tutor.

You can also pickle them or even use shelve for random access 
retrieval later (see the pickle and shelve module docs)

If you have lots of CDs - like thousands! - you might be better 
off with a database because then you can do sophisticated 
searches. But OTOH iTunes works pretty well just using a folder 
structure! :-)

> I am sure this has an obvious and easy answer but I just cannot find  
> it anywhere!

Actually no. Saving and retrieving object instances (known as 
persisting objects in OOP speak) was one of the biggest challenges 
facing the OOP paradigm when it got started in the real world. Many 
different solutions have evolved from flat text files to dedicated Object 
databases, and everyting in between, but it remains a task frought 
with difficulty, especially on large scale projects.

For simpler programs things like Pickle and Shelve are probably the
simplest and best solutions.

HTH,

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



More information about the Tutor mailing list