Introduction To Object
Introduction To Object
Encapsulation involves bundling data with the methods that operate on that data, restricting
direct access to some of the object's components. This helps in protecting the integrity of the data
and prevents unintended interference and misuse.
Inheritance allows a new class to inherit properties and behavior (methods) from an existing
class. This promotes code reuse and can lead to an improved hierarchical structure within your
codebase.
Polymorphism enables objects to be treated as instances of their parent class rather than their
actual class. This is particularly useful for designing flexible and scalable systems.
Abstraction simplifies complex systems by modeling classes appropriate to the problem and
working at the most relevant level of inheritance for a particular aspect of the problem.
To understand these principles in a practical context, let’s design and implement a simple library
management system using OOP principles.
A library management system typically handles tasks like managing books, issuing books to
users, and keeping track of book returns. Let's break down the requirements and identify the
classes needed for this system.
Book Class
python
Copy code
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.status = 'available'
def get_status(self):
return self.status
The Book class encapsulates the data related to a book and provides methods to access and
modify the book's status.
LibraryMember Class
python
Copy code
class LibraryMember:
def __init__(self, member_id, name):
self.member_id = member_id
self.name = name
self.borrowed_books = []
Library Class
python
Copy code
class Library:
def __init__(self):
self.books = []
self.members = []
The Library class manages the collection of books and members. It provides methods to add
books and members, issue books to members, and process returns.
Let's create some books, members, and a library to demonstrate how this system works.
python
Copy code
# Create books
book1 = Book('The Great Gatsby', 'F. Scott Fitzgerald', '1234567890')
book2 = Book('1984', 'George Orwell', '1234567891')
# Create members
member1 = LibraryMember(1, 'Alice')
member2 = LibraryMember(2, 'Bob')
# Create a library
library = Library()
In this example, we instantiate books and members and add them to the library. We then
demonstrate issuing and returning a book using the Library class's methods.
Conclusion