5. Constructing Python – Classes and Methods
Activity 14: Creating Classes and Inheriting from a Parent Class
Solution:
- Firstly, define the parent class,
Polygon
. We add aninit
method that allows the user to specify the lengths of the sides when creating the polygon:class Polygon(): """A class to capture common utilities for dealing with shapes""" def __init__(self, side_lengths): self.side_lengths = side_lengths def __str__(self): return 'Polygon with %s sides' % self.num_sides
- Add two properties to the
Polygon
class – one that computes the number of sides of the polygon, and another that returns the perimeter:class Polygon(): """A class to capture common utilities...