user87337
user87337

Reputation: 3

list as Python class variable

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.

Upvotes: 0

Views: 127

Answers (3)

0x90
0x90

Reputation: 41012

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)

Upvotes: 0

kirbyfan64sos
kirbyfan64sos

Reputation: 10727

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

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34176

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.

Upvotes: 5

Related Questions