Implement a Python Class to Simulate a Library Management System
We will create a simple Python class to simulate a library management system. This system will allow users to add books, delete books, find books, and list all books. Each book will contain two attributes: title and author.
Example
class
Book:
def
init
(
self
,
title
,
author
)
:
self
.
title
=
title
self
.
author
=
author
def
str
(
self
)
:
return
f
"{self.title} by {self.author}"
class
Library:
def
init
(
self
)
:
self
.
books
=
[
]
def
add_book
(
self
,
title
,
author
)
:
new_book
=
Book
(
title
,
author
)
self
.
books
.
append
(
new_book
)
(
f
"Added: {new_book}"
)
def
remove_book
(
self
,
title
)
:
for
book
in
self
.
books
:
if
book.
title
==
title:
self
.
books
.
remove
(
book
)
(
f
"Removed: {book}"
)
return
(
f
"Book with title '{title}' not found."
)
def
find_book
(
self
,
title
)
:
for
book
in
self
.
books
:
if
book.
title
==
title:
(
f
"Found: {book}"
)
return
book
(
f
"Book with title '{title}' not found."
)
return
None
def
list_books
(
self
)
:
if
not
self
.
books
:
(
"No books in the library."
)
else
:
(
"Books in the library:"
)
for
book
in
self
.
books
:
(
book
)
Example usage
library
=
Library
(
)
library.
add_book
(
"1984"
,
"George Orwell"
)
library.
add_book
(
"To Kill a Mockingbird"
,
"Harper Lee"
)
library.
list_books
(
)
library.
find_book
(
"1984"
)
library.
remove_book
(
"1984"
)
library.
list_books
(
)
Code analysis:
Bookclass: represents a book, containing the title (title) and author (author) attributes.__str__method returns the string representation of the book.Libraryclass: represents the library, containing a list of books (books). Provides the following methods:
add_book(title, author): Add a book to the library.remove_book(title): Delete a book from the library by title.find_book(title): Find a book by title.list_books(): List all books in the library.- Example usage: create a
Libraryinstance, add two books, list all books, find and delete a book, and finally list all books again.
Output result:
Added: 1984 by George Orwell
Added: To Kill a Mockingbird by Harper Lee
Books in the library:
1984 by George Orwell
To Kill a Mockingbird by Harper Lee
Found: 1984 by George Orwell
Removed: 1984 by George Orwell
Books in the library:
To Kill a Mockingbird by Harper Lee
Python3 Examples