0

I want a class "Library" which has a class variable "books" which is a list of all the books in the library. So may class begins

class Library:
    books = []

Now I want to add a book to my collection, but I can find no syntax to do so. The model I have in my head is something like

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

which I would expect to call with something like from the main routine with something like

lib = Library()
b = Book(author, title)
lib.addBook(b)

However, I've not been able to find any way to do this. I always get an error with the "append" where I try to add the book to the list.

1
  • the way you are doing it, books is a class variable. Commented Mar 22, 2014 at 16:14

3 Answers 3

5

You should declare books as an instance variable, not a class variable:

class Library:
    def __init__(self):
        self.books = []

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

so you can create an instance of Library:

lib = Library()
b = Book(...)
lib.addBook(b)

Notes:

  • For further information about self , you can read this post.
  • This assumes your Book class is implemented correctly.
Sign up to request clarification or add additional context in comments.

Comments

0
class Library():
    def __init__(self):
        self.books = []
    def addBook(self, book):
        self.books.append(book)

Comments

0

look at this example for the initialization and the setter:

class Library:
    def __init__(self):
        self.books = []
    def add(self, x):
        self.books.append(x)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.