KEMBAR78
Abhishek Assignment 3 | PDF | Banking | Financial Services
0% found this document useful (0 votes)
28 views5 pages

Abhishek Assignment 3

Uploaded by

karankaran7704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views5 pages

Abhishek Assignment 3

Uploaded by

karankaran7704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

ASSIGNMENT:- 03

1. Class Creation: Write a class Book with attributes title, author, and pages. Include a method
to display book details.
Ans. class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def display_details(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Pages: {self.pages}")
if __name__ == "__main__":
my_book = Book("1984", "George Orwell", 328)
my_book.display_details()
2. Encapsulation: Create a class Bank Account with private attributes for balance. Implement
methods to deposit and withdraw, ensuring proper validation.
Ans. class BankAccount:
def __init__(self):
self.__balance = 0.0 # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: ${amount:.2f}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0:
if amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew: ${amount:.2f}")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def get_balance(self):
return self.__balance
if __name__ == "__main__":
account = BankAccount()
account.deposit(100.0)
account.withdraw(50.0)
print(f"Current Balance: ${account.get_balance():.2f}")
account.withdraw(100.0)
3. Inheritance: Define a class Animal with a method speak (). Create subclasses Dog and Cat
that implement the speak () method.
Ans. class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
if __name__ == "__main__":
dog = Dog()
cat = Cat()
print(f"Dog says: {dog.speak()}")
print(f"Cat says: {cat.speak()}")
4. Method Overriding: Implement a class Vehicle with a method fuel_type().Create
subclasses Car and Truck that override this method.
Ans. class Vehicle:
def fuel_type(self):
raise NotImplementedError("Subclasses must implement this method")
class Car(Vehicle):
def fuel_type(self):
return "Petrol"
class Truck(Vehicle):
def fuel_type(self):
return "Diesel"
if __name__ == "__main__":
my_car = Car()
my_truck = Truck()
print(f"Car fuel type: {my_car.fuel_type()}")
print(f"Truck fuel type: {my_truck.fuel_type()}")
5. Class vs Instance Variables: Write a class Counter that counts the number of instances
created using both class and instance variables.
Ans. class Counter:
instance_count = 0
def __init__(self):
Counter.instance_count += 1
self.instance_id = Counter.instance_count
@classmethod
def get_total_instances(cls):
return cls.instance_count

def get_instance_id(self):
return self.instance_id
if __name__ == "__main__":
counter1 = Counter()
counter2 = Counter()
counter3 = Counter()
print(f"Total instances created: {Counter.get_total_instances()}")
print(f"Instance ID of counter1: {counter1.get_instance_id()}")
print(f"Instance ID of counter2: {counter2.get_instance_id()}")
print(f"Instance ID of counter3: {counter3.get_instance_id()}")

6. Static Methods: Create a class Math Operations with a static method multiply ()
that multiplies two numbers.
Ans. class MathOperations:
@staticmethod
def multiply(a, b):
return a * b
if __name__ == "__main__":
result = MathOperations.multiply(7, 9)
print(f"7 multiplied by 9 is: {result}")
7. Abstract Classes: Use the ABC module to define an abstract class Shape with an abstract
method area (). Create subclasses Circle and Square.
Ans. from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
if __name__ == "__main__":
circle = Circle(5)
square = Square(4)
print(f"Area of the circle: {circle.area():.2f}")
print(f"Area of the square: {square.area():.2f}")

8. Composition: Design a class Library that contains a list of Book objects.


Implement methods to add and remove books.
Ans. class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"'{self.title}' by {self.author}, {self.pages} pages”

class Library:
def __init__(self):
self.books = []
def add_book(self, book):
if isinstance(book, Book):
self.books.append(book)
print(f"Added: {book}")
else:
print("Only Book objects can be added.")

def remove_book(self, title):


for book in self.books:
if book.title == title:
self.books.remove(book)
print(f"Removed: {book}")
return
print(f"Book titled '{title}' not found in the library.")
def list_books(self):
if not self.books:
print("The library is empty.")
else:
print("Books in the library:")
for book in self.books:
print(book)

if __name__ == "__main__":
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()
library.remove_book("1984")
library.list_books()
library.remove_book("The Great Gatsby")
9. POLYMORPHISM: Create a base class Animal with a method speak(). Implement
subclasses Dog, Cat, and Bird that override the speak() method. Demonstrate polymorphism by
creating a list of Animal objects and calling their speak() method.
Ans. class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Bird(Animal):
def speak(self):
return "Chirp!"
if __name__ == "__main__":
animals = [Dog(), Cat(), Bird()]
for animal in animals:
print(f"The {animal.__class__.__name__} says: {animal.speak()}")

10. POLYMORPHISM: Create a base class Shape with a method draw(). Implement
subclasses Square,Triangle, and Circle. Create a function that takes a list of shapes and calls their
draw() method.
Ans. class Shape:
def draw(self):
raise NotImplementedError("Subclasses must implement this method")
class Square(Shape):
def draw(self):
return "Drawing a Square”
class Triangle(Shape):
def draw(self):
return "Drawing a Triangle"
class Circle(Shape):
def draw(self):
return "Drawing a Circle"
def draw_shapes(shapes):
for shape in shapes:
print(shape.draw())
if __name__ == "__main__":
shapes = [Square(), Triangle(), Circle()]
draw_shapes(shapes)

You might also like