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
- The math module is imported to access the value of pi (math.pi), which is required for calculating the area of the circle.
- 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.
- 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.
- An instance of the Circle class is created with a radius value of 10.
- The calculate_area method is called on the circle object, which calculates the area of the circle using the provided formula.
- 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
Create 5 different Python Classes and access them via a single class object.
Create 5 Python classes and set up multilevel inheritance among all the classes.
Set Instance variable data with setattr and getattr methods.
Python oops program with encapsulation.
Create a Python class called Rectangle with attributes length and width.
Create a Python class called Circle with attributes radius.