Statement
Solution
Python Exercise 8.1: The Circle Class
Object-Oriented Programming (OOP) lets you bundle data and behaviour together in a class. Write a Circle class that stores a radius and can calculate its area and circumference.
Your class should:
- Define a class called
Circle. - Include an
__init__method that accepts aradiusparameter and stores it as an instance attribute. - Include an
area()method that returnsπ × radius². Usemath.pifor π. - Include a
circumference()method that returns2 × π × radius. - Create an instance of
Circlewith a radius of7and print both values rounded to 2 decimal places.
Sample Interaction:
Input
Output
(None)
Area: 153.94
Circumference: 43.98
Solution
We define the class with an __init__ constructor and two methods, then create an object and call each method.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
# Create an instance with radius 7
c = Circle(7)
print(f"Area: {c.area():.2f}")
print(f"Circumference: {c.circumference():.2f}")
Key Concepts:
class ClassName:defines a new class.__init__is the constructor — it runs automatically when an object is created.selfrefers to the current instance of the class.- Instance attributes (e.g.
self.radius) store data specific to each object. :.2finside an f-string rounds a float to 2 decimal places.
Test Console
Run code to see output...