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

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • What is Python library Complete List of Python Libraries

    In Python, a library is a collection of pre-written code that you can use in your programs. Think of it like a toolbox full of specialized tools. Instead of building every tool from scratch, you can use the tools (functions, classes, modules) provided by a library to accomplish tasks more efficiently.   Here’s a breakdown…

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

Leave a Reply

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