Python Code Example: Volume of a Cube

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:

  • An instance attribute for the side length
  • A method to calculate the volume
  • Object instantiation and calling the volume method

Python Code Example:

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()}")

Expected Output

The volume of the cube is: 64

Code Explanation

  1. Defining the Cube class
    • The class contains an __init__ method that initializes the side_length attribute when an object is created.
  2. Creating the volume method
    • This method calculates the volume using the formula: Volume = side3
  3. Creating an object of the class
    • We instantiate a Cube object with side_length=4.
  4. Calling the volume method
    • The volume() method is called, which returns 43 = 64, and the result is printed.