39. Problem to create a single inheritance example in Python

In this Python oops program, we will create an single inheritance example in Python. Class called Manager that inherits from the Employee class.

Single inheritance example in Python

Steps to solve the program
  1. The Employee class is defined with a constructor method __init__ that takes name and salary as parameters and initializes the instance variables self.name and self.salary with the provided values.
  2. The class also has a method print_details that prints the employee’s name and salary.
  3. The Manager class is defined as a subclass of Employee class, inheriting its attributes and methods.
  4. The Manager class has an additional constructor method __init__ that takes name, salary, department, and bonus as parameters. It calls the superclass’s __init__ method using super() to initialize the name and salary attributes inherited from the Employee class, and initializes the department and bonus attributes with the provided values.
  5. The Manager class also has a method calculate_total_compensation that calculates the total compensation of the manager by adding their salary and bonus.
  6. The code creates an object manager of the Manager class by calling its constructor and passing the name “John Walker”, salary 60000, department “Sales”, and bonus 5000 as arguments.
  7. The calculate_total_compensation method is called on the manager object, which calculates the total compensation by adding the salary and bonus.
  8. The total compensation is then printed using the print statement.
  9. Thus, we have created a single inheritance example in Python.
				
					class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def print_details(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

class Manager(Employee):
    def __init__(self, name, salary, department, bonus):
        super().__init__(name, salary)
        self.department = department
        self.bonus = bonus
    
    def calculate_total_compensation(self):
        total_compensation = self.salary + self.bonus
        return total_compensation

# Create an object of the Manager class
manager = Manager("John Walker", 60000, "Sales", 5000)
total_compensation = manager.calculate_total_compensation()
print("Total Compensation:", total_compensation)
				
			

Output:

				
					Total Compensation: 65000
				
			

Related Articles

Create a Python class called Employee with attributes name and salary.

Create a Python class called Customer with attributes name and balance.

38. Problem to create employee class in Python

In this Python oops program, we will create employee class in Python. Include a method to print the employee’s name and salary.

Create Employee class in Python

Steps to solve the program
  1. The Employee class is defined with a constructor method __init__ that takes name and salary as parameters and initializes the instance variables self.name and self.salary with the provided values.
  2. The class also has a method print_details that prints the employee’s name and salary.
  3. The code creates an object employee of the Employee class by calling its constructor and passing the name “John Walker” and salary 50000 as arguments.
  4. The print_details method is called on the employee object, which prints the employee’s name and salary.
				
					class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def print_details(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

# Create an object of the Employee class
employee = Employee("John Walker", 50000)
employee.print_details()
				
			

Output:

				
					Name: John Walker
Salary: 50000
				
			

Related Articles

Create a Python class called Shape with a method to calculate the area of the shape.

Create a Python class called Manager that inherits from the Employee class.

37. Problem to create a shape class in Python

In this Python oops program, we will create a shape class in Python. Python class called Shape with a method to calculate the area of the shape.

Create a shape class in Python

Steps to solve the program
  1. The Shape class in Python is defined as a base class. It has a method calculate_area, which is left undefined (implemented as pass). This method will be overridden in the derived classes.
  2. The Square class is derived from the Shape class. It has a constructor method __init__ that takes the side_length as a parameter and initializes the instance variable self.side_length.
  3. The class overrides the calculate_area method inherited from the Shape class. It calculates the area of a square by multiplying the side_length by itself (side_length ** 2).
  4. The Triangle class is derived from the Shape class. It has a constructor method __init__ that takes the base and height as parameters and initializes the instance variables self.base and self.height.
  5. The class overrides the calculate_area method inherited from the Shape class. It calculates the area of a triangle using the formula 0.5 * base * height.
  6. The code creates objects square and triangle of the Square and Triangle classes, respectively, by passing the required parameters to their constructors.
  7. The calculate_area method is called on each object, and the calculated areas are printed.
				
					class Shape:
    def calculate_area(self):
        pass

class Square(Shape):
    def __init__(self, side_length):
        self.side_length = side_length
    
    def calculate_area(self):
        return self.side_length ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def calculate_area(self):
        return 0.5 * self.base * self.height

# Create objects of the Square and Triangle classes
square = Square(5)
triangle = Triangle(4, 6)
print("Square Area:", square.calculate_area())
print("Triangle Area:", triangle.calculate_area())
				
			

Output:

				
					Square Area: 25
Triangle Area: 12.0
				
			

Related Articles

Create a Python class called Course with attributes name, teacher, and students.

Create a Python class called Employee with attributes name and salary.

36. Problem to create a Python class real world example

In this Python oops program, we will create a Python class real world example. Python class called Course with attributes name, teacher, and students.

Python class real world example

Steps to solve the program
  1. The Course class has a constructor method __init__ that takes two parameters: name and teacher. It initializes the instance variables self.name, self.teacher, and self.students. The self.students variable is initialized as an empty list.
  2. The class also has three methods:
    The add_student method appends a student to the self.students list.
    The remove_student method removes a student from the self.students list if the student is present.
    The print_details method prints the course name, teacher’s name, and the list of students enrolled in the course.
  3. The code creates an object course of the Course class with the name “Python” and the teacher’s name “Mr. Dipesh Yadav”.
  4. Two students, “John Walker” and “Jade Smith”, are added to the course using the add_student method.
  5. The print_details method is called on the course object, which prints the course details, including the course name, teacher’s name, and the list of enrolled students.
  6. The remove_student method is called to remove the student “Jade Smith” from the course.
  7. The print_details method is called again to print the updated course details.
  8. Thus, we have created a Python class real world example.
				
					class Course:
    def __init__(self, name, teacher):
        self.name = name
        self.teacher = teacher
        self.students = []
    
    def add_student(self, student):
        self.students.append(student)
    
    def remove_student(self, student):
        if student in self.students:
            self.students.remove(student)
    
    def print_details(self):
        print("Course Name:", self.name)
        print("Teacher:", self.teacher)
        print("Students:")
        for student in self.students:
            print("- ", student)

# Create an object of the Course class
course = Course("Python", "Mr. Dipesh Yadav")
course.add_student("John walker")
course.add_student("Jade Smith")
course.print_details()
course.remove_student("Jade Smith")
course.print_details()

				
			

Output:

				
					Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
-  John walker
-  Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
-  John walker
				
			

Related Articles

Create a Python class called StudentRecord with attributes name, age, and grades.

Create a Python class called Shape with a method to calculate the area of the shape.

35. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called StudentRecord with attributes name, age, and grades.

Python class example

Steps to solve the program
  1. The StudentRecord class has a constructor method __init__ that takes three parameters: name, age, and grades. It initializes the instance variables self.name, self.age, and self.grades with the provided values.
  2. The class also has a method called calculate_average_grade which calculates the average grade of the student. It sums up all the grades in the self.grades list, divides it by the number of grades, and returns the average grade.
  3. The print_details method prints the student’s name, age, and average grade by calling the calculate_average_grade method.
  4. The code creates an object student of the StudentRecord class with the name “John Snow”, age 20, and a list of grades [80, 90, 85, 95].
  5. The print_details method is called on the student object, which prints the student’s details, including their name, age, and average grade.
  6. Thus, we have created a Python class example.
				
					class StudentRecord:
    def __init__(self, name, age, grades):
        self.name = name
        self.age = age
        self.grades = grades
    
    def calculate_average_grade(self):
        total_grades = sum(self.grades)
        average_grade = total_grades / len(self.grades)
        return average_grade
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        print("Average Grade:", self.calculate_average_grade())

# Create an object of the StudentRecord class
student = StudentRecord("John show", 20, [80, 90, 85, 95])
student.print_details()
				
			

Output:

				
					Name: John show
Age: 20
Average Grade: 87.5
				
			

Related Articles

Create a Python class called ElectricCar that inherits from the Car class.

Create a Python class called Course with attributes name, teacher, and students.

34. Problem to create an inheritance real life example in Python

In this Python oops program, we will create an inheritance real life example in Python. Python class called ElectricCar that inherits from the Car class.

Inheritance real life example 

Steps to solve the program
  1. The Car class represents a general car and has a constructor method __init__ that takes three parameters: make, model, and year. It initializes the instance variables self.make, self.model, and self.year with the provided values.
  2. The class also has a print_details method that prints the make, model, and year of the car.
  3. The ElectricCar class is a subclass of Car and represents an electric car. It extends the Car class by adding two additional attributes: battery_size and range_per_charge.
  4. The __init__ method of the ElectricCar class takes the same parameters as the Car class, as well as the new attributes specific to electric cars. It calls the superclass’s (Car) __init__ method using super() to initialize the inherited attributes.
  5. The calculate_range method calculates the range of the electric car based on the battery size and range per charge.
  6. The code creates an object electric_car of the ElectricCar class with the make “Tesla”, model “Model S”, year 2022, battery size 75, and range per charge 5.
  7. The calculate_range method is called on the electric_car object, which calculates the range of the electric car.
  8. The calculated range is stored in the variable range and printed.
  9. Thus, we have created an inheritance real life example.
				
					class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    
    def print_details(self):
        print("Make:", self.make)
        print("Model:", self.model)
        print("Year:", self.year)
        

class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size, range_per_charge):
        super().__init__(make, model, year)
        self.battery_size = battery_size
        self.range_per_charge = range_per_charge
    
    def calculate_range(self):
        return self.battery_size * self.range_per_charge

# Create an object of the ElectricCar class
electric_car = ElectricCar("Tesla", "Model S", 2022, 75, 5)
range = electric_car.calculate_range()
print("Range:", range)

				
			

Output:

				
					Range: 375
				
			

Related Articles

Create a Python class called Car with attributes make, model, and year.

Create a Python class called StudentRecord with attributes name, age, and grades.

33. Problem to create an OOPS example in Python

In this Python oops program, we will create an OOPS example in Python. Python class called Car with attributes make, model, and year.

OOPS example in Python

Steps to solve the program
  1. The Car class has a constructor method __init__ that takes three parameters: make, model, and year. It initializes the instance variables self.make, self.model, and self.year with the provided values.
  2. The print_details method prints the details of the car, including the make, model, and year. It retrieves the values of the instance variables and prints them with descriptive labels.
  3. The code creates an object car of the Car class with the make “Mahindra”, model “Thar”, and year 2021.
    The print_details method is called on the car object, which prints the details of the car.

				
					class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    
    def print_details(self):
        print("Make:", self.make)
        print("Model:", self.model)
        print("Year:", self.year)

# Create an object of the Car class
car = Car("Mahindra", "Thar", 2021)
car.print_details()

				
			

Output:

				
					Make: Mahindra
Model: Thar
Year: 2021
				
			

Related Articles

Create a Python class called CheckingAccount that inherits from the BankAccount class.

Create a Python class called ElectricCar that inherits from the Car class.

32. Problem to create an inheritance example using Python

In this Python oops program, we will create an inheritance example using Python. Python class called CheckingAccount that inherits from the BankAccount class.

Inheritance example using Python

Steps to solve the program
  1. The BankAccount class has a constructor method __init__ that takes two parameters: account_number and balance. It initializes the instance variables self.account_number and self.balance with the provided values.
  2. The deposit method allows depositing money into the account. It takes an amount parameter, increases the account balance by that amount, and prints a success message along with the new balance.
  3. The withdraw method allows withdrawing money from the account. It takes an amount parameter and checks if the account balance is sufficient to cover the requested withdrawal amount. If so, it deducts the amount from the balance and prints a success message with the new balance. If the account balance is insufficient, it prints a message indicating the withdrawal is denied.
  4. The CheckingAccount class is a subclass of BankAccount and inherits its attributes and methods. It introduces two additional attributes: transaction_limit and transaction_fee. The constructor method __init__ of CheckingAccount calls the superclass’s __init__ method using super() to initialize the inherited attributes.
  5. The withdraw method is overridden in the CheckingAccount class to include additional validation specific to checking accounts. It calls the check_transaction_limit method to check if the withdrawal amount is within the transaction limit. If the withdrawal amount is valid and the account balance is sufficient to cover the withdrawal amount plus the transaction fee, it calls the superclass’s withdraw method to perform the withdrawal. If not, it prints a message indicating that the withdrawal is denied due to insufficient funds.
  6. The code creates an object checking_account of the CheckingAccount class with an account number of “1234567890”, an initial balance of 1000, a transaction limit of 500, and a transaction fee of 10.
  7. The withdraw method is called twice on the checking_account object. The first withdrawal is for an amount of 400, which is within the transaction limit and the available balance. The second withdrawal is for an amount of 600, which exceeds the transaction limit, resulting in a transaction fee being deducted. However, the account balance is insufficient to cover the withdrawal amount plus the transaction fee, so the withdrawal is denied.
  8. Thus, we have created an inheritance example using Python.
				
					class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print("Deposit of", amount, "successful. New balance:", self.balance)
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print("Withdrawal of", amount, "successful. New balance:", self.balance)
        else:
            print("Insufficient funds. Withdrawal denied.")

class CheckingAccount(BankAccount):
    def __init__(self, account_number, balance, transaction_limit, transaction_fee):
        super().__init__(account_number, balance)
        self.transaction_limit = transaction_limit
        self.transaction_fee = transaction_fee
    
    def check_transaction_limit(self, amount):
        if amount <= self.transaction_limit:
            print("Transaction within limit.")
        else:
            print("Transaction exceeds limit. Transaction fee will be deducted.")

    def withdraw(self, amount):
        self.check_transaction_limit(amount)
        if self.balance >= amount + self.transaction_fee:
            super().withdraw(amount + self.transaction_fee)
        else:
            print("Insufficient funds. Withdrawal denied.")

# Create an object of the CheckingAccount class
checking_account = CheckingAccount("1234567890", 1000, 500, 10)
checking_account.withdraw(400)
checking_account.withdraw(600)

				
			

Output:

				
					Transaction within limit.
Withdrawal of 410 successful. New balance: 590
Transaction exceeds limit. Transaction fee will be deducted.
Insufficient funds. Withdrawal denied.
				
			

Related Articles

Create a Python class called SavingsAccount that inherits from the BankAccount class.

Create a Python class called Car with attributes make, model, and year.

31. Problem to create an inheritance example in real life.

In this Python oops program, we will create an inheritance example in real life. In this program, a class called SavingsAccount inherits from the BankAccount class.

Inheritance example in real life

Steps to solve the program
  1. The BankAccount class has a constructor method __init__ that takes two parameters: account_number and balance. It initializes the instance variables self.account_number and self.balance with the provided values.
  2. The deposit method allows depositing money into the account. It takes an amount parameter, increases the account balance by that amount, and prints a success message along with the new balance.
  3. The withdraw method allows withdrawing money from the account. It takes an amount parameter and checks if the account balance is sufficient to cover the requested withdrawal amount. If so, it deducts the amount from the balance and prints a success message with the new balance. If the account balance is insufficient, it prints a message indicating the withdrawal is denied.
  4. The SavingsAccount class is a subclass of BankAccount and inherits its attributes and methods. It introduces two additional attributes: interest_rate and minimum_balance. The constructor method __init__ of SavingsAccount calls the superclass’s __init__ method using super() to initialize the inherited attributes.
  5. The calculate_interest method calculates and prints the interest earned on the account balance based on the provided interest_rate.
  6. The withdraw method is overridden in the SavingsAccount class to include additional validation specific to savings accounts. It checks if the withdrawal amount allows the account to maintain the minimum required balance. If the withdrawal is within the limits, it calls the superclass’s withdraw method to perform the withdrawal. If not, it prints a message indicating that the withdrawal is denied due to not meeting the minimum balance requirement.
  7. An object of the SavingsAccount class is created with an account number of “1234567890”, an initial balance of 1000, an interest rate of 2.5%, and a minimum balance requirement of 500. The savings_account variable refers to this object.
  8. The calculate_interest method is called on the savings_account object, which calculates and prints the interest earned based on the account balance and interest rate.
  9. The withdraw method is called on the savings_account object with an amount of 800. It checks if the withdrawal amount maintains the minimum required balance and calls the superclass’s withdraw method if valid. In this case, the withdrawal is allowed, so the superclass’s withdraw method is called and a success message is printed with the new balance.
  10. Thus, we have created an Inheritance example in real life.
				
					class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print("Deposit of", amount, "successful. New balance:", self.balance)
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print("Withdrawal of", amount, "successful. New balance:", self.balance)
        else:
            print("Insufficient funds. Withdrawal denied.")

class SavingsAccount(BankAccount):
    def __init__(self, account_number, balance, interest_rate, minimum_balance):
        super().__init__(account_number, balance)
        self.interest_rate = interest_rate
        self.minimum_balance = minimum_balance
    
    def calculate_interest(self):
        interest = self.balance * (self.interest_rate / 100)
        print("Interest:", interest)
    
    def withdraw(self, amount):
        if self.balance - amount >= self.minimum_balance:
            super().withdraw(amount)
        else:
            print("Withdrawal denied. Minimum balance requirement not met.")

# Create an object of the SavingsAccount class
savings_account = SavingsAccount("1234567890", 1000, 2.5, 500)
savings_account.calculate_interest()
savings_account.withdraw(800)

				
			

Output:

				
					Interest: 25.0
Withdrawal denied. Minimum balance requirement not met.
				
			

Related Articles

Create a Python class called BankAccount with attributes account_number and balance.

Create a Python class called CheckingAccount that inherits from the BankAccount class.

30. Problem to create a class in Python

In this Python oops program, we will create a class in Python. A class called BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account.

Create a class in Python

Steps to solve the program
  1. The BankAccount class has a constructor method __init__ that takes two parameters, account_number and balance. It initializes the instance variables self.account_number and self.balance with the provided values.
  2. The deposit method allows depositing money into the account. It takes an amount parameter and increases the account’s balance by that amount. It then prints a success message along with the new balance.
  3. The withdraw method allows withdrawing money from the account. It takes an amount parameter and checks if the account balance is sufficient to cover the requested withdrawal amount. If so, it deducts the amount from the balance and prints a success message with the new balance. If the account balance is insufficient, it prints a message indicating the withdrawal is denied.
  4. An object of the BankAccount class is created with an account number of “1234567890” and an initial balance of 1000. The account variable refers to this object. The deposit method is called on the account object with an amount of 500, which increases the balance to 1500 and prints a success message.
  5. Then, the withdraw method is called with an amount of 2000, which is higher than the available balance. It prints an insufficient funds message indicating that the withdrawal is denied.

				
					class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print("Deposit of", amount, "successful. New balance:", self.balance)
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print("Withdrawal of", amount, "successful. New balance:", self.balance)
        else:
            print("Insufficient funds. Withdrawal denied.")

# Create an object of the BankAccount class
account = BankAccount("1234567890", 1000)
account.deposit(500)
account.withdraw(2000)
				
			

Output:

				
					Deposit of 500 successful. New balance: 1500
Insufficient funds. Withdrawal denied.
				
			

Related Articles

Create a Python class called Cat that inherits from the Animal class.

Create a Python class called SavingsAccount that inherits from the BankAccount class.