Inheritance in OOP Python: Rectangle & Cuboid Example

Rectangle

# Define a class named 'Rectangle'
class Rectangle:
    """
    A class to represent a rectangle and calculate its area.
    """

    # The constructor method to initialize the object with length and width
    def __init__(self, length, width):
        """
        Initializes a Rectangle object.

        Args:
            length (float): The length of the rectangle.
            width (float): The width of the rectangle.
        """
        self.length = length
        self.width = width

    # A method to calculate the area of the rectangle
    def calculate_area(self):
        """
        Calculates and returns the area of the rectangle.

        Returns:
            float: The area of the rectangle.
        """
        return self.length * self.width

# --- Example Usage ---

# Create an instance (an object) of the Rectangle class
# We'll create a rectangle with a length of 10 and a width of 5
try:
    my_rectangle = Rectangle(10, 5)

    # Call the calculate_area method on our object
    area = my_rectangle.calculate_area()

    # Print the result
    print(f"The area of the rectangle is: {area}")

except Exception as e:
    print(f"An error occurred: {e}")

# You can create another rectangle with different dimensions
try:
    another_rectangle = Rectangle(7.5, 3.2)
    area_2 = another_rectangle.calculate_area()
    print(f"The area of the second rectangle is: {area_2}")

except Exception as e:
    print(f"An error occurred: {e}")





Inheritance in OOP Python: Rectangle & Cuboid Example

Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is a type of Rectangle, so it makes sense for it to inherit from it.


📂 Program Breakdown

In this example, we’ll use a Rectangle class as the parent and a Cuboid class as the child. The Cuboid will inherit everything from Rectangle and add its own specific properties and methods, such as height.

📜 Python Program

Python

# Parent class 🧑‍💻
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

# Child class 👶
class Cuboid(Rectangle):
    def __init__(self, length, width, height):
        # Call the parent class's constructor
        #super().__init__(length, width)
        self.height = height

    def volume(self):
        return self.area() * self.height

    def surface_area(self):
        return 2 * (self.area() + (self.length * self.height) + (self.width * self.height))

# Create an instance of the Cuboid class 📦
cuboid = Cuboid(10, 5, 4)

# Accessing methods from both parent and child classes
print(f"The area of the cuboid's base is: {cuboid.area()}")
print(f"The volume of the cuboid is: {cuboid.volume()}")
print(f"The surface area of the cuboid is: {cuboid.surface_area()}")

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[3], line 30
     27 cuboid = Cuboid(10, 5, 4)
     29 # Accessing methods from both parent and child classes
---> 30 print(f"The area of the cuboid's base is: {cuboid.area()}")
     31 print(f"The volume of the cuboid is: {cuboid.volume()}")
     32 print(f"The surface area of the cuboid is: {cuboid.surface_area()}")

Cell In[3], line 8, in Rectangle.area(self)
      7 def area(self):
----> 8     return self.length * self.width

AttributeError: 'Cuboid' object has no attribute 'length'

🔍 Key Concepts

  • Rectangle Class: This is our parent class. It provides the foundational properties (length, width) and methods (area, perimeter) that the child class can reuse.
  • Cuboid Class: This is our child class, inheriting from Rectangle. The (Rectangle) in the class definition is the key.
  • super().__init__(): This function is a lifesaver! It calls the __init__ method of the parent class, which automatically initializes length and width for us. This saves you from rewriting code ✍️.
  • Method Reusability: The Cuboid class’s volume() method demonstrates a key benefit of inheritance. It calls the parent’s area() method to calculate its volume, saving you from writing the area formula again.

Inheritance allows you to create specialized classes that build upon general ones, promoting clean, organized, and reusable code ✨.

Similar Posts

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Class Variables Andmethds

    Class Variables Class variables are variables that are shared by all instances of a class. They are defined directly within the class but outside of any method. Unlike instance variables, which are unique to each object, a single copy of a class variable is shared among all objects of that class. They are useful for…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

Leave a Reply

Your email address will not be published. Required fields are marked *