You need to fill the other required args in Book
as they do not have a value. Parameters without a default value are required, if you don't define them while calling the class, you will get an error. Secondly, for the number
arg in Book
, you gave it a string instead, and for the title
arg in Book
you put an int. I'm pretty sure these were mistakes and you mixed up title
and number
. Thirdly, as the Book
class is, putting it into a list isn't going to get you any good information about the Book
class and its params, it's just going to give you the default string representation of the class, which is <__main__.Book object at [idk what this is]>
. To fix this, you will have to put __str__()
or __repr__()
in your book class. Fourthly, there are no variables in the class Inventory
other than book_list
, you can't access anything else, in this case, it would be very useful to use variables for the books you are putting into the book_list
list to access attributes of the books. Fifthly, there is no book id anywhere, you need that to get your book object. Finally, to answer your original question, you can't, you can only do that using dictionaries ({<book-id>: <book-object>}
), not lists. However, one way to achieve what you are trying to do is to have the number
arg as an index for book_list
to get the book object you are trying to access. Final code:
class Book:
def __init__(self, title, book_id, author=None, genre=None, price=None):
self.book_id = book_id
self.title = title
self.author = author
self.genre = genre
self.price = price
class Inventory:
def __init__(self, Book: Book):
self.book_dict = {}
self.book = Book
self.book_dict.update({str(Book.id) : Book.title})
def display_books(self):
for x in self.book_dict:
print(self.book_dict[x])
def find_book_by_id(self, book_id):
return self.book_dict[str(book_id)]