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

标签 python

我设置了一个 Point 类和 Rectangle 类,下面是代码:

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

这两个点是矩形的左上角和右下角。如何从两点求出这个矩形的面积和周长?将不胜感激任何和所有的帮助!

最佳答案

我们可以访问每个点的 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

或者使用方法

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

    def make_perimeter(self):
        self.perimeter = (self.height + self.width) * 2
        return self.perimeter

    def make_area(self):
        self.area = self.height * self.width
        return self.area

rect = Rectangle(Point(3,10),Point(4,8))
print(rect.height)
print(rect.width)
print(rect.make_perimeter())
print(rect.make_area())

关于python - 如何求定义有两点的矩形的面积和周长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472477/

相关文章:

python - 使用 Tensorflow 的目标数组形状与预期输出不同

python - 获取数据帧列中字典的所有键

python - python中的手动直方图

python - 使用 Python Pandas 读取 .txt 文件 - 字符串和 float

Python:使用协程进行异步 HTTP 请求-响应?

python - 如何将整个列表分配给 Pandas 数据框的每一行

python - 带有 Python 的 SOAP API

python - 如何使用逗号分隔变量?

python - 在经过训练的文档集上计算查询字符串的 TF-IDF

python - 使用 tensorflow 在简单的分类数据上获得惊人的准确性