Challenge Summary: Inheritance – Polygon and Triangle Classes

Challenge Summary: Inheritance – Polygon and Triangle Classes

Objective:

Create two classes where Triangle inherits from Polygon and calculates area using Heron’s formula.


1. Polygon Class (Base Class)

Properties:

  • number_of_sides – Number of sides in the polygon
  • sides – List of dimensions for each side

Methods:

__init__(self, num_sides, *sides)

  • Takes number of sides and variable-length side dimensions
  • Stores them as instance variables

python

class Polygon:
    def __init__(self, num_sides, *sides):
        self.number_of_sides = num_sides
        self.sides = list(sides)

2. Triangle Class (Derived Class)

Inheritance:

  • Inherits from Polygon class

Methods:

__init__(self, *sides)

  • Takes three side dimensions as parameters
  • Calls parent constructor with num_sides=3 and the three sides

area(self)

  • Calculates area using Heron’s formula
  • Formula:
    • s = (a + b + c) / 2 (semi-perimeter)
    • area = √[s(s-a)(s-b)(s-c)]

python

import math

class Triangle(Polygon):
    def __init__(self, *sides):
        # Call parent constructor with 3 sides
        super().__init__(3, *sides)
    
    def area(self):
        a, b, c = self.sides  # Get the three sides
        s = (a + b + c) / 2   # Calculate semi-perimeter
        return math.sqrt(s * (s - a) * (s - b) * (s - c))

3. Testing Instructions:

  1. Create a Triangle object with three side lengths
  2. Call the area() method to calculate and display the area
  3. Verify the calculation is correct

Example Usage:

python

# Create triangle with sides 10, 15, 9
triangle = Triangle(10, 15, 9)
print(f"Area: {triangle.area():.2f}")

Key Points:

  • Inheritance: Triangle IS-A Polygon (inherits all properties)
  • Constructor Chaining: Triangle constructor calls Polygon constructor
  • Heron’s Formula: Used to calculate area from three sides
  • Variable Arguments: *sides allows flexible number of parameters

import math

class Polygon:

    def __init__(self, ns, *sides):
        self.no_of_sides = ns
        self.sides = sides[:ns]


class Triangle(Polygon):

    def __init__(self, ns, *sides):
        Polygon.__init__(self, ns, *sides)

    def area(self):
        a, b, c = self.sides
        s = (a + b + c)/2
        area = math.sqrt(s * (s-a) * (s-b) * (s-c))
        return area


t1 = Triangle(3, 10, 15, 9, 12, 15, 20)
print('Area:', t1.area())

Similar Posts

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

Leave a Reply

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