计算多边形的周长-----面对对象编程

使用面对对象编程,隐藏细节,对坐标轴上的多边形的周长进行计算

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Polygon:
    def __init__(self):
        self.vertices = []

    def add_point(self, point):
        self.vertices.append(point)

    def distance(self, point1, point2):
        return math.sqrt((point1.x - point2.x)**2 + (point1.y - point2.y)**2)

    def perimeter(self):
        perimeter = 0
        for i in range(len(self.vertices)):
            # range是左包含,右不包含
            perimeter += self.distance(self.vertices[i], self.vertices[(i+1) % (len(self.vertices))])
        return perimeter

polygon = Polygon()
polygon.add_point(Point(1, 1))
polygon.add_point(Point(1, 2))
polygon.add_point(Point(3, 2))
polygon.add_point(Point(3, 1))

print(polygon.perimeter())


将多边形的顶点和多边形本身都做成一个对象,利用math模块进行周长计算

但是,从上面看,API并不是很紧凑,要是一次能接受多个所有顶点然后计算出来就好了,那么,请看改良版::

import math

class Polygon:
    def __init__(self, *args):
        self.vertices = args

    def distance(self, point1, point2):
        return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)

    def perimeter(self):
        perimeter = 0
        for i in range(len(self.vertices)):
            # range是左包含,右不包含
            perimeter += self.distance(self.vertices[i], self.vertices[(i+1) % (len(self.vertices))])
        # perimeter += self.distance(self.vertices[len(self.vertices)-1], self.vertices[0])
        return perimeter

polygon = Polygon((1, 1), (1, 2), (2, 2), (2, 1))
print(polygon.perimeter())


这个版本,就可以一次接受多边形所有的顶点坐标,然后计算出来周长!

你可能感兴趣的:(计算多边形的周长-----面对对象编程)