[Tutor] associating two objects without ORM and processing a text file

Alan Gauld alan.gauld at btinternet.com
Mon Feb 11 19:19:19 CET 2013


On 11/02/13 05:14, neubyr wrote:
>
> I have a text file with each line in following format:
>
> Book Name, Author Name, Genre, Publication Date
>
> I would like to perform following queries on this file:
>   * Get all books written by an author
>   * Remove all books of an author
>   * Get information about a book (pretty print matching line!)
>   * Get books of particular genre
>
> Also, I would like to add and delete entries in this file. I am not
> planning to use any database for this purpose and would like to get
> better grasp on file parsing and classes/OOP. I need some help in
> creating classes and following are my initial thoughts:
>
> # Create a class for Book object
> class Book:
>    atributes: name, author_name, genre, publication-date
>

Yep, that looks like all you need.


> # Create
> Author:
>   attribute(s): name

No idea why you want this. A waste of space ...

> # Create class for reading and writing to the file
> class Booksfile:
>    methods: ??

You do not create classes for functions. The functions are part of the 
class. You can have a list of Books read from the file as an attribute 
of your Books class. Populate it at program startup and write the edited 
list back at termination. (Or any other time you make a
change for improved robustness)

> * How do I associate/relate Book and Author classes so that it will help
> me in getting information like 'get list of books written by an author'?
> Data attribute?

I woudn't have a separate Author class but, if you must, something like:

class Book:
   def __init__(self, theAuthor,theTitle):
       self.Author = theAuthor
       self.title = theTitle

class Author:
   def __init__(self,aName):
      self.name = aName

myBook = Book(Author('Jane Austin'), 'Pride & Prejudice')

> * Should I create a new Booksfile object for reading, writing and
> deleting entries in the file OR add corresponding methods to the book
> object itself?

Instance methods in the Book for reading/writing single lines
Class methods in Book for reading/writing the entire file
(or standalone functions could also be used) into a bookList class 
attribute.

> I am not planning to use SQLite or any database and would like to use
> text file only. Appreciate any help on designing such application.

As a learning exercise that's fine, for any real world problem it would 
be foolish. This is what databases were built for...

HTH

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



More information about the Tutor mailing list