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.

29. Problem to show inheritance of classes in Python

In this Python oops program, we will create classes to show inheritance of classes in Python. This code demonstrates the concept of inheritance of classes in Python.

Inheritance of classes in Python

Steps to solve the program
  1. The Animal class has a constructor method __init__ that takes two parameters, name and color. Inside the constructor, the values of name and color are assigned to the instance variables self.name and self.color, respectively. This class also defines a method print_details that prints the name and color of the animal.
  2. The Cat class is a subclass of Animal, as indicated by (Animal) in its class definition. It adds two additional attributes, breed and weight, which represent the cat’s breed and weight, respectively. The class overrides the print_details method inherited from Animal and extends it by calling the print_details method of the superclass using super().print_details(), and then printing the cat’s breed and weight.
  3. An object of the Cat class is created with the name “Whiskers”, color “Gray”, breed “Persian”, and weight 15.
  4. The cat variable now refers to this object. The print_details method is then called on the cat object, which executes the overridden print_details method in the Cat class. This method first calls the print_details method of the Animal class using super().print_details() to print the animal’s name and color, and then prints the cat’s breed and weight.
				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)

class Cat(Animal):
    def __init__(self, name, color, breed, weight):
        super().__init__(name, color)
        self.breed = breed
        self.weight = weight
    
    def print_details(self):
        super().print_details()
        print("Breed:", self.breed)
        print("Weight:", self.weight)

# Create an object of the Cat class
cat = Cat("Whiskers", "Gray", "Persian", 15)
cat.print_details()
				
			

Output:

				
					Name: Whiskers
Color: Gray
Breed: Persian
Weight: 15
				
			

Related Articles

Create a Python class called Student that inherits from the Person class.

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

28. Problem to show inheritance in Python with example

In this Python oops program, we will create a class to show inheritance in Python with example. This code demonstrates the concept of inheritance

Inheritance in Python

Steps to solve the program
  1. The Person class has a constructor method __init__ that takes two parameters, name and age. Inside the constructor, the values of name and age are assigned to the instance variables self.name and self.age, respectively. This class also defines a method print_details that prints the name and age of the person.
  2. The Student class is a subclass of Person, as indicated by (Person) in its class definition. It adds two additional attributes, student_id and grades, which represent the student’s ID and grades, respectively. The class overrides the print_details method inherited from Person and extends it by calling the print_details method of the superclass using super().print_details(), and then printing the student ID.
  3. An object of the Student class is created with the name “Jade Smith”, age 24, student ID “A12345”, and grades [‘A’, ‘A+’]. The student variable now refers to this object.
  4. The print_details method is then called on the student object, which executes the overridden print_details method in the Student class. This method first calls the print_details method of the Person class using super().print_details() to print the person’s name and age, and then prints the student ID.

				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        
class Student(Person):
    def __init__(self, name, age, student_id, grades):
        super().__init__(name, age)
        self.student_id = student_id
        self.grades = grades
    
    def print_details(self):
        super().print_details()
        print("Student ID:", self.student_id)

# Create an object of the Student class
student = Student("Jade Smith", 24, "A12345", ['A','A+'])
student.print_details()
				
			

Output:

				
					Name: Jade Smith
Age: 24
Student ID: A12345
				
			

Related Articles

Create a Python class called Person with attributes name and age.

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

27. Problem to create a class with attributes in Python

In this Python oops program, we will create a class with attributes in Python. This code demonstrates the basic functionality of the Person class, allowing you to create person objects, store their name and age, and print their details.

Create a class with attributes 

Steps to solve the program
  1. The Person class is defined with a constructor method __init__. The constructor takes two parameters, name and age, which represent the name and age of the person, respectively. Inside the constructor, the values of name and age are assigned to the instance variables self.name and self.age, respectively.
  2. The class also defines a method named print_details. This method simply prints the name and age of the person using the print function.
  3. An object of the Person class is created by calling the constructor with the arguments “John Snow” and 28.
  4. The person variable now refers to this object.
  5. The print_details method is called on the person object, which prints the details of the person.
				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)

# Create an object of the Person class
person = Person("John Snow", 28)
person.print_details()
				
			

Output:

				
					Name: John Snow
Age: 28
				
			

Related Articles

Create a Python class called Circle with attributes radius.

Create a Python class called Student that inherits from the Person class.

26. Problem to calculate area of circle using class in Python

In this Python oops program, we will create a example to calculate area of circle using class in Python. This code demonstrates the basic functionality of the Circle class, allowing you to create circle objects, calculate their area and circumference, and retrieve the results.

Area of circle using class in Python

Steps to solve the program
  1. The code begins by importing the math module, which provides mathematical functions and constants.
  2. The class Circle is defined with a constructor method __init__. The constructor takes one parameter, radius, which represents the radius of the circle. Inside the constructor, the value of radius is assigned to the instance variable self.radius.
  3. The class also defines two additional methods: calculate_area and calculate_circumference. The calculate_area method calculates the area of the circle using the formula pi * radius^2, where pi is the mathematical constant pi (approximately 3.14159). The method returns the calculated area.
  4. The calculate_circumference method calculates the circumference of the circle using the formula 2 * pi * radius, and returns the result.
  5. An object of the Circle class is created by calling the constructor with the argument 10. The circle variable now refers to this object.
  6. The calculate_area method is called on the circle object and the result is stored in the area variable.
  7. The calculate_circumference method is called on the circle object and the result is stored in the circumference variable.
  8. The area and circumference are then printed using the print function.
				
					import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def calculate_area(self):
        return math.pi * self.radius**2
    
    def calculate_circumference(self):
        return 2 * math.pi * self.radius

# Create an object of the Circle class
circle = Circle(10)
area = circle.calculate_area()
circumference = circle.calculate_circumference()
print("Area:", area)
print("Circumference:", circumference)
				
			

Output:

				
					Area: 314.1592653589793
Circumference: 62.83185307179586
				
			

Related Articles

Create a Python class called Rectangle with attributes length and width.

Create a Python class called Person with attributes name and age.

25. Problem to calculate area of rectangle using class in Python

In this Python oops program, we will create an example to calculate area of rectangle using class in Python. This code demonstrates the basic functionality of the Rectangle class, allowing you to create rectangle objects, calculate their area and perimeter, and retrieve the results.

Area of rectangle using class in Python

Steps to solve the program
  1. The code defines a class named Rectangle with a constructor method __init__. The constructor takes two parameters: length and width. Inside the constructor, the values of length and width are assigned to the instance variables self.length and self.width, respectively.
  2. The class also defines two additional methods: calculate_area and calculate_perimeter. The calculate_area method calculates the area of the rectangle by multiplying the length and width, and returns the result. The calculate_perimeter method calculates the perimeter of the rectangle using the formula 2 * (length + width), and returns the result.
  3. An object of the Rectangle class is created by calling the constructor with the arguments 5 and 13. The rectangle variable now refers to this object.
  4. The calculate_area method is called on the rectangle object and the result is stored in the area variable.
  5. The calculate_perimeter method is called on the rectangle object and the result is stored in the perimeter variable.
  6. The area and perimeter are then printed using the print function.
				
					class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def calculate_area(self):
        return self.length * self.width
    
    def calculate_perimeter(self):
        return 2 * (self.length + self.width)

# Create an object of the Rectangle class
rectangle = Rectangle(5, 13)
area = rectangle.calculate_area()
perimeter = rectangle.calculate_perimeter()
print("Area:", area)
print("Perimeter:", perimeter)
				
			

Output:

				
					Area: 65
Perimeter: 36
				
			

Related Articles

Python oops program with encapsulation.

Create a Python class called Circle with attributes radius.

24. Problem to show encapsulation in Python

In this Python oops program, we will create a class to show encapsulation in Python. This example showcases the concept of private variables and methods in Python classes. 

Encapsulation in Python

Steps to solve the program
  1. The code defines a class named MyClass with a private instance variable __private_var and a private method __private_method.
  2. The double underscores before the variable and method names indicate that they are intended to be private, meaning they are intended to be used within the class only and not accessed directly from outside the class.
  3. An instance of the MyClass class is created and assigned to the variable obj.
  4. The public_method of the obj object is called. This method is a public method, which means it can be accessed from outside the class.
  5. Inside the public_method, the private method __private_method is called using self.__private_method().
  6. The private method __private_method prints “Private method” when called.
				
					class MyClass:
    def __init__(self):
        self.__private_var = 10
    
    def __private_method(self):
        print("Private method")

    def public_method(self):
        print("Public method")
        self.__private_method()

# Create an object of the class
obj = MyClass()

# Access public method and variable
obj.public_method()
				
			

Output:

				
					Public method
Private method
				
			

Related Articles

Set Instance variable data with setattr and getattr methods.

Create a Python class called Rectangle with attributes length and width.

23. Problem to example of setattr and getattr in Python

In this Python oops program, we will create a class to show example of setattr and getattr in Python. This example demonstrates how to dynamically set and get instance variables using the setattr and getattr in Python functions.

Setattr and getattr in Python

Steps to solve the program
  1. The code defines a class named MyClass with an empty constructor (__init__ method).
  2. An instance of the MyClass class is created and assigned to the variable obj.
  3. The setattr function is used to dynamically set an instance variable on the obj object. The first argument to setattr is the object on which we want to set the variable (obj), the second argument is the name of the variable as a string (“variable”), and the third argument is the value we want to assign to the variable (“Value”).
  4. The getattr function is used to dynamically get the value of an instance variable from the obj object. The first argument to getattr is the object from which we want to get the variable value (obj), and the second argument is the name of the variable as a string (“variable”). The value of the variable is then assigned to the value variable.
  5. Finally, the value of the instance variable is printed, which will output “Value” in this case.

				
					class MyClass:
    def __init__(self):
        pass

# Create an object of the class
obj = MyClass()

# Set instance variable dynamically
setattr(obj, "variable", "Value")

# Get instance variable dynamically
value = getattr(obj, "variable")
print(value)

				
			

Output:

				
					Value
				
			

Related Articles

Create 5 Python classes and set up multilevel inheritance among all the classes.

Python oops program with encapsulation.