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.

22. Problem to show multilevel inheritance example in multiple classes

In this Python oops program, we will show multilevel inheritance example in multiple classes. This example demonstrates the concept of class inheritance and method overriding in Python. 

Multilevel Inheritance Example

Steps to solve the program
  1. Five classes (Class1, Class2, Class3, Class4, and Class5) are defined. Each class is derived from its respective parent class, forming an inheritance hierarchy.
  2. Each class has a single method that prints a specific message.
  3. An object (obj) of the final class, Class5, is created.
  4. By creating an instance of Class5, we have access to all the methods defined in Class5, as well as the methods inherited from its parent classes (Class4, Class3, Class2, and Class1).
  5. The methods are called using dot notation on the obj object.
				
					class Class1:
    def method1(self):
        print("Method 1 of Class 1")

class Class2(Class1):
    def method2(self):
        print("Method 2 of Class 2")

class Class3(Class2):
    def method3(self):
        print("Method 3 of Class 3")

class Class4(Class3):
    def method4(self):
        print("Method 4 of Class 4")

class Class5(Class4):
    def method5(self):
        print("Method 5 of Class 5")

# Create an object of the final class and access methods
obj = Class5()
obj.method1()
obj.method2()
obj.method3()
obj.method4()
obj.method5()

				
			

Output:

				
					Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3
Method 4 of Class 4
Method 5 of Class 5
				
			

Related Articles

Create 5 different Python Classes and access them via a single class object.

Set Instance variable data with setattr and getattr methods.

21. Problem to create multiple classes in Python

In this Python oops program, we will create multiple classes in Python and access them using a single class. This example illustrates a way to handle objects of different classes using type-checking and conditional statements.

Create multiple classes in Python

Steps to solve the program
  1. Five classes (Class1, Class2, Class3, Class4, and Class5) are defined, each with a single method that prints a specific message.
  2. A list named classes is created, which contains instances of the five defined classes.
  3. A loop iterates over each object (obj) in the classes list.
    Inside the loop, conditional statements (if, elif) are used to check the type of the object using the isinstance() function. Depending on the object’s class, the corresponding method is called using dot notation.
  4. For example, if the object is an instance of Class1, the method1() of Class1 is called.
  5. This pattern repeats for each class, ensuring that the appropriate method is called for each object.

				
					class Class1:
    def method1(self):
        print("Method 1 of Class 1")

class Class2:
    def method2(self):
        print("Method 2 of Class 2")

class Class3:
    def method3(self):
        print("Method 3 of Class 3")

class Class4:
    def method4(self):
        print("Method 4 of Class 4")

class Class5:
    def method5(self):
        print("Method 5 of Class 5")

# Create a class object
classes = [Class1(), Class2(), Class3(), Class4(), Class5()]

# Access methods of different classes via the class object
for obj in classes:
    if isinstance(obj, Class1):
        obj.method1()
    elif isinstance(obj, Class2):
        obj.method2()
    elif isinstance(obj, Class3):
        obj.method3()
    elif isinstance(obj, Class4):
        obj.method4()
    elif isinstance(obj, Class5):
        obj.method5()
				
			

Output:

				
					Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3
Method 4 of Class 4
Method 5 of Class 5
				
			

Related Articles

Python Class structure with module-level Import.

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

20. Problem to show class structure in Python with module-level import

In this Python oops program, we will create a class to show class structure in Python with module-level import. This example demonstrates a simple implementation of a Circle class that encapsulates the radius and provides a method to calculate the area of the circle.

Class structure in Python

Steps to solve the program
  1. The math module is imported to access the value of pi (math.pi), which is required for calculating the area of the circle.
  2. The Circle class is defined with a constructor (__init__ method) that takes a radius parameter. The radius value is assigned to the self.radius attribute of the instance.
  3. The calculate_area method is defined within the Circle class. It calculates the area of the circle using the formula: pi * radius^2, where pi is accessed from the math module, and radius is obtained from the self.radius attribute of the instance. The calculated area is returned as the result.
  4. An instance of the Circle class is created with a radius value of 10.
  5. The calculate_area method is called on the circle object, which calculates the area of the circle using the provided formula.
  6. The calculated area is stored in the area variable.
    Finally, the area is printed with the help of the print statement.

				
					import math

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

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

Output:

				
					Area of the circle: 314.1592653589793
				
			

Related Articles

Python Class with @property decorator.

Create 5 different Python Classes and access them via a single class object.