I'm a beginner working on a library management system and there's something I can't get my head around.
So I have a Books class that creates new book records.
class Books:def __init__(self, title=None, author=None, year=None, publisher=None, num_copies=None,num_available_copies=None, publication_date=None):self.bookID = random.randint(1, 1000)self.title = titleself.author = authorself.year = yearself.publisher = publisherself.num_copies = num_copiesself.num_available_copies = num_available_copiesself.publication_date = publication_date
I then have to define another class 'BookList' which has the following requirement: 'Define a method to store a collection (e.g., dictionary). The collection should store book instances that are created from the Book object.' How do I do that?
Following your request exactly would result in this new class:
class BookList:def __init__(self):self.list_of_books = []def add_book(self, book: Books):self.list_of_books.append(book)
This is not exactly the best way to do python. But I guess anything goes in a learning scenario. For a slightly better implementation of all of this refer to the code below:
from dataclasses import dataclass@dataclass
class Book:book_id : inttitle : strauthor : stryear : intpublisher : strnum_copies : intnum_available_copies : intpublication_date : intclass BookList:def __init__(self):self._books = []@propertydef books(self):return self._books@books.setterdef books(self, book):if isinstance(book, Book):self._books.append(book)
now using it will be like this:
>>> book_list = BookList()
>>> book_list.books
[]
>>> book_list.add_book(Book(Bunch of parameters here))
>>> book_list.books
[Book(Parameters from the book you made)]
you can do a lot more than what I did, I added the properties so that if you decide to copy this code to pass some kind of school class, you'll have some explaining to do. Otherwise good luck!