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

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • (?),Greedy vs. Non-Greedy, Backslash () ,Square Brackets [] Metacharacters

    The Question Mark (?) in Python Regex The question mark ? in Python’s regular expressions has two main uses: 1. Making a Character or Group Optional (0 or 1 occurrence) This is the most common use – it makes the preceding character or group optional. Examples: Example 1: Optional ‘s’ for plural words python import re pattern…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

Leave a Reply

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