简体   繁体   中英

Python: How do lists within classes work?

I've been trying to practice with classes in Python, and I've found some areas that have confused me. The main area is in the way that lists work, particularly in relation to inheritance.

Here is my Code.

class LibraryItem:
    def __init__(self, book_id, name):
        self.item_id = book_id
        self.name = name

class Library(LibraryItem):
    books=[]
        def all_books(books):
            bookslen = len(books)
            return bookslen

        def add_book(books):
            books.append(self.book_id)

What I'm trying to get the program to do is allow me to store an instance of a book_id and name, which can then be added to the list books[], via the add_books method in the child class Library.

I don't think inheritance is what your looking for here

You have i library and this library contains a list of books. keep it simple.

class Library:

    ## creates the library
    def __init__(self):
        self.books = []

    ## returns number of books
    def number_of_books(self):
        return len(self.books)

    ## adds a book to the list of books 
    def add_book(self, book):
       self.books.append(book)


class Book:

    ## creates your book
    def __init__(self, item_id, name):
        self.item_id = item_id
        self.name = name


localLibrary = Library() # create the library
new_book = Book(1,"Harry Potter") # create the book
localLibrary.add_book(new_book) # add the book to the library
print(localLibrary.number_of_books()) # display the number of books

## output -> 1 book in the library

I think this is what you trying to achieve

class LibraryItem:
    def __init__(self, book_id, name):
        self.item_id = book_id
        self.name = name

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

    def __len__(self):
        return len(self.books)

    def add_book(self, book):
        self.books.append(book.book_id)

now you can create instance of book and add it to library:

book1 = LibraryItem(1,"To Kill a Mockingbird")
library = Library()
library.add_book(book1)
print(len(library ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM