In object-oriented programming (OOP), we use classes and objects to model real-world entities. A cube is a three-dimensional shape where all sides are equal in length. The volume of a cube is calculated using the formula:
Volume = side3
In this example, we will create a Cube class in Python that includes:
class Cube:
"""Class to represent a cube and calculate its volume."""
def __init__(self, side_length):
"""Constructor to initialize the side length."""
self.side_length = side_length
def volume(self):
"""Method to calculate the volume of the cube."""
return self.side_length ** 3
# Creating a Cube object with side length 4
cube = Cube(4)
# Calculating and displaying the volume
print(f"The volume of the cube is: {cube.volume()}")
The volume of the cube is: 64
Cube
class__init__
method that initializes the side_length
attribute when an object is created.volume
methodCube
object with side_length=4
.volume
methodvolume()
method is called, which returns 43 = 64, and the result is printed.