49.Example Programs using Classes

create class Arith to do arithmetic operation.It contains a member function read() to read the two numbers and add() method to find the sum. You can add more methods to the class to incorporate more functionality.
class Arith:
    def read(self):
        self.x=int(input("enter first number.."))
        self.y=int(input("enter second number..."))
    def add(self):
        print("sum=",self.x+self.y)

#creating an object
A=Arith()
#calling the methods
A.read()
A.add()
create a class Rectangle .A constructor is used to initialize the object values. Member function area() to compute the area of the rectangle ( university question)
class Rectangle:
    def __init__(self,length=0,breadth=0):
        self.length=length
        self.breadth=breadth
    def area(self):
        print("area=",self.length*self.breadth)
R1=Rectangle(10,20)
R1.area()
R2=Rectangle(12,13)
R2.area()
Create a class car with attributes model, year and price and a method cost() for displaying the prize. Create two instance of the class and call the method for each instance.(university question)
class Car:
     def __init__(self,model,year,prize):
        self.model=model
        self.year=year
        self.prize=prize
     def cost(self):
        print("Prize of the car=",self.prize)
C1=Car("Maruti",2004,200000)
C2=Car("Ford",2014,5000000)
C1.cost()
C2.cost()
Create a class student with attribute name and roll number and a method dataprint() for displaying the same. Create two instance of the class and call the method for each instance.( university question)
class Student:
    def __init__(self,name,rno):
        self.name=name
        self.rno=rno
    def dataprint(self):
        print("Name=",self.name)
        print("Rno=",self.rno)
s1=Student("devi",101)
s2=Student("anjana",102)
s1.dataprint()
s2.dataprint()
Create a class Person with attributes name, age salary and a method display() for showing the details. Create two instances of the class and call the method for each instance.
class Person:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary
    def display(self):
        print("Name=",self.name)
        print("Age=",self.age)
        print("Salary=",self.salary)
s1=Person("devi",30,10100)
s2=Person("anjana",35,10200)
s1.display()
s2.display()

Define a class Mobile to store the details of a Mobile (company, model,price) with the following methods.
a) set_details()- to set the values to the data attributes
b)display_details()-to display the data attribute values
Create an object of the class and invoke methods. ( university question)
class Mobile:
    def set_details(self):
        self.company=input("enter compnay name...")
        self.model=input("enter model name..")
        self.price=float(input("enter price.."))
    def display_details(self):
        print("Company Name=",self.company)
        print("Model=",self.model)
        print("Price=",self.price)
M=Mobile()
M.set_details()
M.display_details();
Define a class in Python to store the details of students( rollno, mark1,mark2) with the following methods
readData()- to assign values to class attributes
computeTotal()-to find the total marks
printDetails()- to print the attribute values and total marks.
Create an object of this class and invoke the methods. ( Univesrsity question)
class Student:
    def readData(self):
        self.rollno=int(input("enter roll number..."))
        self.mark1=int(input("enter mark1.."))
        self.mark2=int(input("enter mark2.."))
    def computeTotal(self):
        self.total=self.mark1+self.mark2
    def printDetails(self):
        print("roll number-->",self.rollno)
        print("Mark1-------->",self.mark1)
        print("Mark2-------->",self.mark2)
        print("Total Marks---",self.total)
S=Student()
S.readData()
S.computeTotal()
S.printDetails()
Define a class in Python to store the details of book( title,author,cost) with the following methods
get_details()- to assign values to class attributes
print_details()- to display the attribute values
Create an object of this class and invoke the methods. ( University question)
class Book:
    def get_details(self):
        self.title=input("enter book title...")
        self.auth=input("enter author..")
        self.cost=int(input("enter cost.."))
    def print_details(self):
        print("Book Tile-->",self.title)
        print("Author-------->",self.auth)
        print("Cost-------->",self.cost)
B=Book()
B.get_details()
B.print_details()

How can a class be instantiated in Python? Write a Python program to express the instances as return values to define a class RECTANGLE with parameters height, width, corner_x, and corner_y and member functions to find center, area, and perimeter of an instance.
class RECTANGLE:
    def read(self):
        self.height=int(input("enter height of rectangle.."))
        self.width=int(input("enter width of rectangle.."))
        self.corner_x=int(input("enter right corner x..."))
        self.corner_y=int(input("enter right corner y..."))
    def center(self):
        self.corner_x1=self.corner_x-self.width
        self.corner_y1=self.corner_y+self.height
        print("Center={},{}".format((self.corner_x+self.corner_x1)/2,(self.corner_y+self.corner_y1)/2))
    def area(self):
        print("Area=",self.height*self.width)
    def perimeter(self):
        print("Perimeter=",2*(self.height+self.width))
        
#creating an object
R=RECTANGLE()
#calling the methods
R.read()
R.center()
R.area()
Write Python program to create a class called as Complex and implement __add__( ) method to add two complex numbers. Display the result by overloading the + Operator. ( university question)
class Complex:
    def __init__(self,a=0,b=0):
        self.a=a
        self.b=b
    def display(self):
        if self.b>0:
            print("complex number is ",self.a, "+",self.b, "j")
        else:
            print("complex number is ",self.a,self.b, "j")
    def __add__(self,other):
        r=self.a+other.a
        i=self.b+other.b
        return Complex(r,i)
        
c1=Complex(2,-3)
c2=Complex(3,4)
c3=c1+c2
c1.display()
c2.display()
c3.display()

Write a Python class which has two methods get_distance and print_distance.get_distance accept a distance in kilometres from the user and print_distance print the distance in meter. ( university question)

class Distance:
    def get_distance(self):
        self.dist=int(input("enter distance in kilometer."))
    def print_distance(self):
        print("Distance in Meter",self.dist*1000)

#creating an object
D=Distance()
#calling the methods
D.get_distance()
D.print_distance()

Create a class student with name, roll number, marks of 3 subjects and total marks as attributes. read_data() ,display_data() and compute_total() should be the three methods. Write a python program to create 2 objects of the class, read, display and calculate the total marks. ( university question)
class Student:
    def read_data(self):
        self.rollno=int(input("Enter roll number:"))
        self.name=input("Enter name:")
        self.mark1=int(input("Enter mark1:"))
        self.mark2=int(input("Enter mark2:"))
        self.mark3=int(input("Enter mark3:"))
    def compute_total(self):
        self.total=self.mark1+self.mark2+self.mark3
    def display_data(self):
        print("Roll number-->",self.rollno)
        print("Name-->",self.name)
        print("Mark1-------->",self.mark1)
        print("Mark2-------->",self.mark2)
        print("Mark2-------->",self.mark3)
        print("Total Marks---",self.total)
S1=Student()
S1.read_data()
S1.compute_total()
S2=Student()
S2.read_data()
S2.compute_total()
S1.display_data()
S2.display_data()

Consider a Rectangle Class and create two Rectangle Objects. Write Python program to check whether the area of the first rectangle is greater than second by overloading > operator. ( university question)

class Rectangle:
    def __init__(self,l=0,b=0):
        self.l=l
        self.b=b
        self.area=self.l*self.b
    def display(self):
        print("Area of rectangle ",self.area)
    def __gt__(self,other):
        return self.area > other.area
                
r1=Rectangle(5,3)
r2=Rectangle(3,4)
r1.display()
r2.display()
if r1>r2:
    print('area of rectangle r1 is larger')
else:
    print('area of rectangle r2 is larger')

Write a Python program to define a class Rectangle with parameters height, width and member functions to find area, and perimeter of it. ( University question)
class Rectangle:
    def __init__(self,h,w):
        self.height=h
        self.width=w
    def area(self):
        self.area=self.height*self.width
        print("Area=",self.area)
    def perimeter(self):
        self.peri=2*self.height*self.width
        print("Perimeter=",self.peri)

R=Rectangle(4,5)
R.area()
R.perimeter()

Create a Student class and initialize it with name and roll number. ( university question)
Make methods to :
1. Display - Display all information of the student.
2. setAge - Assign age to student
3. setTestMarks - Assign marks of a test to the student.

class Student:
    def __init__(self,name,rollno):
        self.name=name
        self.rollno=rollno
    def setAge(self,age):
        self.age=age
        
    def setTestMarks(self,mark):
        self.mark=mark

    def __str__(self):
        return "rollno={},Name={},Age={},Mark={}".format(self.rollno,self.name,self.age,self.mark)
S=Student("Ardra",101)
S.setAge(20)
S.setTestMarks(45)
print(S)

Define a class Mobile to store the details of mobile ( company, model and price) with the following methods
i) set_details() - to set the values to the data attributes
ii)display_details()- to display the attribute values
Create an object of the class and invoke the methods.

class Mobile:
    def __init__(self):
        # Initialize data attributes with default values
        self.company = None
        self.model = None
        self.price = None

    def set_details(self, company, model, price):
        """
        Set the values for the mobile's details.
        """
        self.company = company
        self.model = model
        self.price = price

    def display_details(self):
        """
        Display the mobile's details.
        """
        print(f"Company: {self.company}")
        print(f"Model: {self.model}")
        print(f"Price: {self.price}")


# Create an object of the Mobile class
my_mobile = Mobile()

# Set the details of the mobile
my_mobile.set_details("Samsung", "Galaxy S23", 79999)

# Display the details of the mobile
my_mobile.display_details()


Design a Python class Counter with the following methods: increment() (increases the counter by 1),decrement()(decreases the counter by 1), and get_value()(returns the current counter value).Ensure the counter cannot go below zero.( university question)

class Counter:
    def __init__(self):
        self.value = 0   # Initialize counter at 0

    def increment(self):
        self.value += 1  # Increase by 1

    def decrement(self):
        if self.value > 0:   # Ensure it does not go below 0
            self.value -= 1

    def get_value(self):
        return self.value    # Return current counter value


# Example usage:
c = Counter()
c.increment()
c.increment()
print(c.get_value())  # Output: 2
c.decrement()
print(c.get_value())  # Output: 1
c.decrement()
c.decrement()         # This won't decrease below 0
print(c.get_value())  # Output: 0

Design a class Vehicle with attributes like speed and engine_on.Add a method start() to turn on the engine and print a message. ( university question)

class Vehicle:
    def __init__(self, speed=0):
        self.speed = speed       # Speed of the vehicle
        self.engine_on = False   # Engine status (off by default)

    def start(self):
        if not self.engine_on:
            self.engine_on = True
            print("Engine started. Ready to go!")
        else:
            print("Engine is already on.")


# Example usage:
car = Vehicle(60)
car.start()   # Output: Engine started. Ready to go!
car.start()   # Output: Engine is already on.

Create a derived class ElectricCar from Vehicle that overrides the start() method and includes a method charge(). Demonstrate how polymorphism works by calling start() from both classes. Also include exception handling for invalid charging input.

class Vehicle:
    def __init__(self, speed=0):
        self.speed = speed
        self.engine_on = False

    def start(self):
        if not self.engine_on:
            self.engine_on = True
            print("Engine started. Ready to go!")
        else:
            print("Engine is already on.")


class ElectricCar(Vehicle):
    def __init__(self, speed=0, battery_level=100):
        super().__init__(speed)
        self.battery_level = battery_level

    # Override start method
    def start(self):
        if self.battery_level > 0:
            if not self.engine_on:
                self.engine_on = True
                print("Electric motor started silently. Battery at", self.battery_level, "%")
            else:
                print("Electric motor is already running.")
        else:
            print("Battery empty! Please charge before starting.")

    # Method to charge the car
    def charge(self, amount):
        try:
            if not isinstance(amount, (int, float)):
                raise ValueError("Charge amount must be a number.")
            if amount <= 0:
                raise ValueError("Charge amount must be greater than 0.")
            if self.battery_level + amount > 100:
                self.battery_level = 100
                print("Battery fully charged (100%).")
            else:
                self.battery_level += amount
                print(f"Battery charged. Current level: {self.battery_level}%")
        except ValueError as e:
            print("Charging Error:", e)


# Demonstration of polymorphism
vehicles = [Vehicle(80), ElectricCar(100, 50)]

for v in vehicles:
    v.start()   # Calls Vehicle.start() for Vehicle, ElectricCar.start() for ElectricCar

# Charging example with exception handling
car = ElectricCar(120, 20)
car.charge(50)     # Valid charging
car.charge(-10)    # Invalid charging → handled by exception
car.charge("abc")  # Invalid charging → handled by exception

Write a class BankAccount with methods deposit() and withdraw().
Raise an exception if withdrawal exceeds balance. ( university question)
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit amount must be positive.")
        self.balance += amount
        print(f"Deposited: {amount}, New Balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal amount must be positive.")
        if amount > self.balance:
            raise Exception("Insufficient balance!")
        self.balance -= amount
        print(f"Withdrew: {amount}, Remaining Balance: {self.balance}")


# Example usage:
account = BankAccount(100)
account.deposit(50)   # Deposited: 50, New Balance: 150

try:
    account.withdraw(70)  # Withdrew: 70, Remaining Balance: 80
    account.withdraw(200)  # Raises Exception
except Exception as e:
    print("Error:", e)

Extend the class to support a subclass SavingsAccount that applies interest during deposit. Demonstrate method overriding and show how exceptions are handled during deposit if the amount is negative. 

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit amount must be positive.")
        self.balance += amount
        print(f"Deposited: {amount}, New Balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal amount must be positive.")
        if amount > self.balance:
            raise Exception("Insufficient balance!")
        self.balance -= amount
        print(f"Withdrew: {amount}, Remaining Balance: {self.balance}")


class SavingsAccount(BankAccount):
    def __init__(self, balance=0, interest_rate=0.05):
        super().__init__(balance)
        self.interest_rate = interest_rate  # Default 5% interest

    # Override deposit method to add interest
    def deposit(self, amount):
        try:
            if amount <= 0:
                raise ValueError("Deposit amount must be positive.")
            interest = amount * self.interest_rate
            total_deposit = amount + interest
            self.balance += total_deposit
            print(f"Deposited: {amount} (+{interest} interest), New Balance: {self.balance}")
        except ValueError as e:
            print("Deposit Error:", e)


# Demonstration
print("---- BankAccount ----")
acc1 = BankAccount(100)
acc1.deposit(50)
try:
    acc1.deposit(-20)  # Will raise ValueError
except Exception as e:
    print("Error:", e)

print("\n---- SavingsAccount ----")
acc2 = SavingsAccount(200, interest_rate=0.1)
acc2.deposit(100)   # Applies 10% interest → Deposited 100 + 10
acc2.deposit(-50)   # Exception handled inside overridden deposit()


Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators