DEV Community

Cover image for Intro to Python: Day 11 - Another Class Inheritance Example
James Hubert
James Hubert

Posted on

Intro to Python: Day 11 - Another Class Inheritance Example

Hi there 👋 I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Today in my journey with boot.dev I encountered a fun problem that we solved using OOP and class-based inheritance.

A rectangle is a shape with four sides where the length of the sides is equal and the length of the top and bottom are equal, but the top and bottom don't need to be equal to the length of the sides.

A square is a type of rectangle, but all four sides must be the same length.

So, if we make a Rectangle class to get the perimeter and area of any given rectangle, where we need to input the length of the x-axis sides and the length of the y-axis sides in order to get that information, like so:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

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

    def get_perimeter(self):
        return (self.length + self.width) * 2
Enter fullscreen mode Exit fullscreen mode

...then we should be able to quickly build a Square class that inherits these methods but is automatically instantiated using only the length of one of its sides (since all sides of a square are the same length):

class Square(Rectangle):
    def __init__(self, length):
        super().__init__(length, length)
Enter fullscreen mode Exit fullscreen mode

Behold, the power of OOP! Unlike dragons and cars and other fairly non-sensical use cases, I could see actually using something like this if I were, say, building a house, maybe. Idk.

If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.

Top comments (0)