Triangle
Triangle
15)
Now we're going to embed the Point class (see Lab 3.4.1.14) inside another class. Also, we're
going to put three points into one class, which will let us define a triangle. How can we do it?
The new class will be called Triangle and this is the list of our expectations:
the constructor accepts three arguments - all of them are objects of the Point class;
the points are stored inside the object as a private list;
the class provides a parameterless method called perimeter(), which calculates the
perimeter of the triangle described by the three points; the perimeter is a sum of all legs'
lengths (we mention it for the record, although we are sure that you know it perfectly
yourself.)
Expected output
3.414213562373095
Answers:
import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
class Triangle:
def __init__(self, point1, point2, point3):
self.points = [point1, point2, point3]
def distance(self, point1, point2):
dx = point1.x - point2.x
dy = point1.y - point2.y
return math.sqrt(dx ** 2 + dy ** 2)
def perimeter(self):
side1 = self.distance(self.points[0], self.points[1])
side2 = self.distance(self.points[1], self.points[2])
side3 = self.distance(self.points[2], self.points[0])
return side1 + side2 + side3
triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
print(triangle.perimeter())
In this code:
We define the Point class as you mentioned, with an __init__ method to initialize x and y
coordinates.
We create a Triangle class with a constructor that takes three Point objects and stores them in a
private list self.points.
We define a distance method within the Triangle class to calculate the distance between two
points using the Pythagorean theorem.
The perimeter method calculates the perimeter of the triangle by summing the lengths of its three
sides.
We create three Point objects and then create a Triangle object using those points.
Finally, we calculate and print the perimeter of the triangle using the perimeter method of the
Triangle object.