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.

Leave a Comment