PDA

View Full Version : Newbie question on containment...


kuber
07-10-2002, 01:04 PM
Ok, say I have 2 classes, one is defined as such:


class book:
def __init__(self, au, na):
self.author = ar
self.name = na
def displayauthor(self):
print self.author
def displayname(self):
print self.name


Now I want to define a class that will be a collection of book objects, but I am not sure how to do this, something like this is all I came up with (incomplete):
(obviously this would only add book w/ key 1)


class collection
def addbook(self, bo):
self.bo[1] = bo.displayname()


This isn't right obviously.. I was wondering how I would do this.. ?

kmj
07-10-2002, 01:17 PM
here's one way to do it:


class bookshelf:
def __init__(self):
self.books = [] # we need a list of books

def addbook(self, book):
self.books.append(book)



It's that easy. Essentially, bookshelf contains a list of books. You could go further by keeping the books sorted or adding whatever other library maintenance functions you may need to the bookshelf class. Note that I had to tell python beforehand that 'books' was going to be a list, which I did in the contructor. If you want more specific info, just ask.

kuber
07-10-2002, 01:28 PM
Ok, cool, here is my current code:



class book:
def __init__(self, au, na):
self.author = au
self.name = na
def displayauthor(self):
print self.author
def displayname(self):
print self.name

class bookshelf:
def __init__(self):
self.books = []
def addbook(self, book):
self.books.append(book)

x = book("asdf", "fdas")
y = bookshelf
y.addbook(x)


I get error:

y.addbook(y,x)
TypeError: unbound method addbook() must be called with instance as first argument

Hmm...

inkedmn
07-10-2002, 01:31 PM
you have :

y = bookshelf


you need to have this:

y = bookshelf()


the constructor doesn't execute unless you have the parentheses there.

kuber
07-10-2002, 01:36 PM
aaaaaaaaaaaaaah..

Duh. I had better put on a pot of tea.

Thanks!

~inkedmn++