> I'd be just such a newbie; I don't understand why it would matter if
I
> left the book instance referencing itself....

It's just kind of sloppy and unnecessary to have self.self

> firstly,  I am trying hard to figure out how to create a new file
with
> the list rather than print to standard out.  I haev done this:

I think you want 'a' instead of 'w+' as the file's mode.  You can also
open and close the file outside of the loop; it would be more
efficient.

> Secondly,  I am wondering how I can get a search algorithm that will
> search by multiple fields here,  so that I can (as one example) sort
> the books out by author and then date,  to present a list of the book
> grouped by authors and having each group presented in a chronological
> order,   or by author and title, grouping all the books up into
authors
> presenting each group alphabetically by title.  Or by publisher and
> date,  or by publisher and code....

So far, we've been using the "key" parameter of list.sort.  If you want
sort criteria more complicated than a single attribute, you can sort
based on a custom comparison function.    Comparison functions compare
two objects (let's call them A and B), and return one of three possible
values:

A is greater than B  => 1
A is less than B => -1
A and B are equal => 0

The built-in function "cmp" can be used to compare objects; behavior is
defined for built-in types:

cmp(0, 1) => -1
cmp("Zylophone", "Abstract") => 1   # alphabetical ordering for strings
cmp( [1,2,3], [1,2,3] ) => 0  # compare sequence elements from left to
right

So another way to do a sort-by-author for your books would be:

  def compare_authors(book1, book2):
      return cmp(book1.author, book2.author)

   books.sort(compare_authors)

A more complicated comparison function might nest two others:

  def compare_dates(book1, book2):
      # Assuming that your dates are either numerical or are strings
for which
      # alphabetical sorting is identical to chronological...
      return cmp(book1.date, book2.date)

  def compare_author_and_date(book1, book2):
       different_authors = compare_authors(book1, book2)
       if different_authors:  # different authors
           return different_authors
       else:  # same author.  sort by date.
           return compare_dates(book1, book2)
  
  books.sort(compare_author_and_date)

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to