Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Create a Class and Compute the Area and the Perimeter of the Circle
When it is required to find the area and perimeter of a circle using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to find the area and perimeter of the circle.
Below is a demonstration for the same −
Example
import math
class CircleCompute:
def __init__(self, radius):
self.radius = radius
def area_calculate(self):
return math.pi * (self.radius ** 2)
def perimeter_calculate(self):
return 2 * math.pi * self.radius
# Create an instance with radius 7
my_instance = CircleCompute(7)
print("The radius entered is:")
print(my_instance.radius)
print("The computed area of circle is:")
print(round(my_instance.area_calculate(), 2))
print("The computed perimeter of circle is:")
print(round(my_instance.perimeter_calculate(), 2))
Output
The radius entered is: 7 The computed area of circle is: 153.94 The computed perimeter of circle is: 43.98
Alternative Implementation with Properties
You can also use properties to make the class more pythonic ?
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return math.pi * (self.radius ** 2)
@property
def perimeter(self):
return 2 * math.pi * self.radius
# Create circle with radius 5
circle = Circle(5)
print(f"Circle with radius: {circle.radius}")
print(f"Area: {circle.area:.2f}")
print(f"Perimeter: {circle.perimeter:.2f}")
Circle with radius: 5 Area: 78.54 Perimeter: 31.42
Explanation
- A class named CircleCompute is defined with methods
area_calculate()andperimeter_calculate(). - The
__init__()method initializes the radius attribute when creating an object. - The area is calculated using the formula ? × r².
- The perimeter (circumference) is calculated using the formula 2 × ? × r.
- An instance of the class is created and methods are called to compute results.
- The alternative implementation uses
@propertydecorator for cleaner syntax.
Conclusion
Using classes to compute circle properties demonstrates object-oriented programming in Python. The class encapsulates radius data and provides methods to calculate area and perimeter efficiently.
Advertisements
