Classs and Object Using Real Time Example Program

Class and Object Using Real-Time Example Program:


Question 1: Create a class Student with name and register_number variables initialized in the constructor. Implement a display method to print the student details. Create two objects (s1 and s2), update their values, and display the information.

Program:
# Define 'Student' class
class Student:
    # Initialize attributes
    def __init__(self):
        self.name = "Rathna"  # Default name
        self.registernumber = "1234"  # Default register number

    # Method to display student info
    def display(self):
        print("Name:", self.name)
        print("Register Number:", self.registernumber)

# Create objects 's1' and 's2'
s1 = Student()
s2 = Student()

# Update 's1' attributes
s1.name = "Priya"
s1.registernumber = "1011"

# Update 's2' attributes
s2.name = "Kiruba"
s2.registernumber = "1012"

# Display details of 's1' and 's2'
s1.display()
s2.display()
Output:
Name: Priya
Register Number: 1011
Name: Kiruba
Register Number: 1012


Question 2: Create a class Fruit with a color attribute initialized using the constructor. Create an object orange and pass its color as a parameter. Print the color of the orange.

Program:
# Define 'Fruit' class
class Fruit:
    # Initialize 'color' attribute
    def __init__(self, color):
        self.color = color

# Create 'Papaya' object with color 'orange'
Papaya = Fruit("orange")

# Print Papaya's color
print("Papaya color:", Papaya.color)
Output:
Papaya color: orange


Question 3: Create a class Calculator with variables a and b initialized in the constructor. Implement methods add, sub, mul, and div to perform addition, subtraction, multiplication, and division. Pass the values of a and b through an object and display the results.

Program:
# Define 'calculator' class
class calculator:
    # Initialize 'number1' and 'number2' attributes
    def __init__(self, a, b):
        self.number1 = a
        self.number2 = b

    # Method to add numbers
    def add(self):
        print("add", self.number1 + self.number2)

    # Method to subtract numbers
    def sub(self):
        print("sub", self.number1 - self.number2)

    # Method to multiply numbers
    def mul(self):
        print("mul", self.number1 * self.number2)

    # Method to divide numbers
    def div(self):
        if self.number2 != 0:
            print("div", self.number1 / self.number2)
        else:
            print("Cannot divide by zero")

# Create 'calc' object with numbers 10 and 5
calc = calculator(10, 5)

# Perform operations
calc.add()
calc.sub()
calc.mul()
calc.div()
Output:
add 15
sub 5
mul 50
div 2.0

Post a Comment

0 Comments