Object-Oriented Programming (OOP) with Free code
Object-Oriented Programming (OOP) concepts like classes, inheritance, encapsulation, and object interaction. Below are the solutions for each of the given scenarios:
Table of Contents
1. Create a Class: Book
Task: Define a class named Book
that has attributes like title
, author
, and pages
. Write a method display_info()
that prints out the book’s details.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Pages: {self.pages}")
# Example usage:
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 180)
book1.display_info()
# Output:
# Title: The Great Gatsby
# Author: F. Scott Fitzgerald
# Pages: 180
2. Bank Account Simulation: BankAccount
Task: Extend the BankAccount
class by adding a method transfer()
that allows transferring money from one account to another.
class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited: {amount}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrawn: {amount}")
else:
print("Insufficient funds")
def transfer(self, amount, other_account):
if amount <= self.balance:
self.withdraw(amount)
other_account.deposit(amount)
print(f"Transferred: {amount} to Account {other_account.account_number}")
else:
print("Insufficient funds for transfer")
# Example usage:
account1 = BankAccount("123456", 500)
account2 = BankAccount("789101", 300)
account1.transfer(200, account2)
# Output:
# Withdrawn: 200
# Deposited: 200
# Transferred: 200 to Account 789101
3. Basic Inheritance: Animal
, Dog
, Cat
Task: Create a base class Animal
with attributes name
and species
and a method make_sound()
. Create two derived classes Dog
and Cat
that override the make_sound()
method with their respective sounds.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
# Example usage:
dog = Dog("Buddy", "Canine")
cat = Cat("Whiskers", "Feline")
print(dog.make_sound()) # Output: Woof!
print(cat.make_sound()) # Output: Meow!
Top 10 Spring Boot Projects You Must Try: Detailed Guide
4. Encapsulation: Student
Task: Define a class Student
that has private attributes for name
and grade
. Provide public methods to get and set the values of these attributes.
class Student:
def __init__(self, name, grade):
self.__name = name # Private attribute
self.__grade = grade # Private attribute
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_grade(self):
return self.__grade
def set_grade(self, grade):
self.__grade = grade
# Example usage:
student = Student("Alice", "A")
print(student.get_name()) # Output: Alice
print(student.get_grade()) # Output: A
student.set_name("Bob")
student.set_grade("B")
print(student.get_name()) # Output: Bob
print(student.get_grade()) # Output: B
- Complete Python Course :Â Click here
- Free Notes :- Click here
- New Project :-https://www.youtube.com/@Decodeit2
- Java Projects – Click here
5. Object Interaction: Library
and Book
Task: Create a class Library
with methods to add_book()
and remove_book()
using the Book
class. Implement a method list_books()
that prints all the books currently in the library.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def display_info(self):
print(f"Title: {self.title}, Author: {self.author}, Pages: {self.pages}")
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
print(f"Added book: {book.title}")
def remove_book(self, title):
for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"Removed book: {title}")
return
print(f"Book not found: {title}")
def list_books(self):
if not self.books:
print("No books in the library.")
else:
print("Books in the library:")
for book in self.books:
book.display_info()
# Example usage:
library = Library()
book1 = Book("1984", "George Orwell", 328)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 281)
library.add_book(book1)
library.add_book(book2)
library.list_books()
# Output:
# Added book: 1984
# Added book: To Kill a Mockingbird
# Books in the library:
# Title: 1984, Author: George Orwell, Pages: 328
# Title: To Kill a Mockingbird, Author: Harper Lee, Pages: 281
library.remove_book("1984")
library.list_books()
# Output:
# Removed book: 1984
# Books in the library:
# Title: To Kill a Mockingbird, Author: Harper Lee, Pages: 281
These examples cover several key aspects of OOP:
- Class Creation: How to define classes and methods.
- Inheritance: Creating subclasses and overriding methods.
- Encapsulation: Using private attributes and public methods to control access.
- Object Interaction: Working with multiple classes and their instances to perform complex tasks.
Checkout these below links !
- Task Management System Using Spring Boot
- Movie Recommendation System Web Application using Django
- SQL Temporary Tables: A Handy Tool for Developers
- How to Read JSON File in Python
- Building a Bookstore with Java Spring Boot and MySQL: Features, Guide, and Insights
Post Comment