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

  • replace(), join(), split(), rsplit(), and splitlines() methods in Python

    1. replace() Method Purpose: Replaces occurrences of a substring with another substring.Syntax: python string.replace(old, new[, count]) Examples: Example 1: Basic Replacement python text = “Hello World” new_text = text.replace(“World”, “Python”) print(new_text) # Output: “Hello Python” Example 2: Limiting Replacements (count) python text = “apple apple apple” new_text = text.replace(“apple”, “orange”, 2) print(new_text) # Output: “orange orange apple”…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle 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…

Leave a Reply

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