[Tutor] associating two objects without ORM and processing a text file
neubyr at gmail.com
Mon Feb 11 23:49:39 CET 2013
On Mon, Feb 11, 2013 at 12:36 PM, Dave Angel <davea at davea.name> wrote:
> On 02/11/2013 01:19 PM, Alan Gauld wrote:
>> On 11/02/13 05:14, neubyr wrote:
>> * 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')
> Big problem with that; then there may be multiple instances of Author,
> representing the same Author. Instead, there needs to be a factory
> function which reuses the same Author objects if an additional book with
> the same author is encountered. Without such an approach, one might as
> well stick with strings, which is what we each recommended.
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Thank you for suggestions - Mitya, Dave and Alan.
I am doing it as a learning exercise and it's not a class assignment. I
have little experience with Ruby and now trying to learn Python. It's not
going to be any production application and I haven't thought about
concurrency problems yet.
Based on suggestions, following is a code snippet that I have right now. I
agree that there isn't any need of separate Author object right now, so I
may remove it as well. I have created a class method 'list_by_author' to
return list of books. I am not sure if class method is right approach to
implement 'list_by_author' function as a class method is typically used as
an alternative constructor. Here I am returning list of objects and not
just an object.
Any suggestions for improving this code will be really useful.
self.name = name
self.author = author
self.genre = genre
self.pubdate = pubdate
# TODO: use csv module
# write/add method
""" Write book info to a file """
""" Return list of books of an author """
bookfile = config.bookfile
books =  # empty list - used as list of Books
# TODO: improve regex
regex = re.compile(author)
with open (bookfile,'r') as f:
for line in f:
# error prone - if name contains comma
l = line.split(',')
# create book object and append it to a list
book = self(*l)
return books # return list of books
self.name = name
""" Get list of books """
books = Book.list_by_author(self.name)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor