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

Leave a Reply

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