# The original class
class Triangle:
def __init__(self, height, width):
self.height = height
self.width = width
@property
def area(self):
return 0.5 * self.height * self.width
# The new class
class Triangle(Triangle):
def __mul__(self, value):
return Triangle(self.height*value, self.width*value)
def __lt__(self, other):
return self.area < other.area
def __repr__(self):
return f'{self.__class__.__name__}(height={self.height}, width={self.width})'
# initialise instances
tri1 = Triangle(5, 5)
tri2 = Triangle(5, 8)
print(tri1)
# scale triangle by multiplication
tri1 *= 2 # same as tri1 = tri1*2
print(tri1)
# compare triangles
tri1 < tri2
Triangle(height=5, width=5) Triangle(height=10, width=10)
False
import math
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def distance_to(self, other):
'''Return the distance to another point instance.'''
x0, y0 = self._x, self._y
x1, y1 = other._x, other._y
return self.distance(x0, y0, x1, y1)
@staticmethod
def distance(x0, y0, x1, y1):
return math.sqrt( (x1-x0)**2 + (y1-y0)**2 )
class Polyline:
def __init__(self, points):
self.points = points
def __len__(self):
return len(self.points)-1
def get_total_length(self):
length = 0
for point0, point1 in zip(self.points, self.points[1:]):
length += point0.distance_to(point1)
return length
pt1 = Point(0,0)
pt2 = Point(0,5)
pt3 = Point(5,5)
poly = Polyline([pt1, pt2, pt3])
print('number of segments:', len(poly))
print('total length:', poly.get_total_length())
number of segments: 2 total length: 10.0
The cell below is for setting the style of this document. It's not part of the exercises.
# Apply css theme to notebook
from IPython.display import HTML
HTML('<style>{}</style>'.format(open('../css/cowi.css').read()))