如何求定义了两点的矩形的面积和周长?

2024-06-26 17:49:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我设置了一个点类和矩形类,代码如下:

import math

class Point:
    """A point in two-dimensional space."""

    def __init__(self, x: float = 0.0, y: float = 0.0)->None:               
        self.x = x
        self.y = y    


    def moveIt(self, dx: float, dy: float)-> None:
        self.x = self.x + dx
        self.y = self.y + dy    

    def distance(self, otherPoint: float): 
        if isinstance(otherPoint, Point):
            x1 = self.x
            y1 = self.y
            x2 = otherPoint.x
            y2 = otherPoint.y

            return ( (x1 - x2)**2 + (y1 - y2)**2 )**0.5    


class Rectangle:
    def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight

这两个点是矩形的左上角和右下角。如何从两点求出这个矩形的面积和周长?感谢任何人的帮助!在


Tags: selfnoneinitdeffloatclasspointx1
1条回答
网友
1楼 · 发布于 2024-06-26 17:49:56

我们可以访问每个点的x和y值,并计算出高度和宽度,从那里我们可以创建计算面积和周长的方法

class Rectangle():
    def __init__(self, topLeft = Point(0,0), bottomRight = Point(1,1)):
        self.topLeft = topLeft
        self.bottomRight = bottomRight
        self.height = topLeft.y - bottomRight.y
        self.width = bottomRight.x - topLeft.x
        self.perimeter = (self.height + self.width) * 2
        self.area = self.height * self.width

rect = Rectangle(Point(3,10),Point(4,8))
print(rect.height)
print(rect.width)
print(rect.perimeter)
print(rect.area)
chrx@chrx:~/python/stackoverflow/9.24$ python3.7 rect.py
2
1
6
2

或者用方法

^{pr2}$

相关问题 更多 >