【问题标题】:Analytic geometry using Python OOP使用 Python OOP 的解析几何
【发布时间】:2019-01-03 23:54:32
【问题描述】:

所以我刚刚第一次深入研究 OOP 编程。我遇到了一个练习,我们应该使用 OOP 编写一个脚本,该脚本创建一个矩形,计算它的面积和周长,以及与第二个矩形重叠的面积。到目前为止,一切都很好,我设法解决了。然而,一旦我解决了它,我检查了给定的解决方案,它看起来像这样:

from copy import copy

class Point:

    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y

    def __repr__(self):
        return '({}, {})'.format(self.x, self.y)


class Rectangle:

    def __init__(self, point, width, height):
        self.point = copy(point)
        self.width = abs(width)
        self.height = abs(height)
        if self.width == 0:
            self.width == 1
        if self.height == 0:
            self.height == 1

    def __repr__(self):
        return '[{}, w = {}, h = {}]'.format(self.point, self.width, self.height)

    def surface_area(self):
        return self.width * self.height

    def circunference(self):
        return 2*(self.width + self.height)

    def bottom_right(self):
        return Point(self.point.x + self.width, self.point.y + self.height)

    def overlap(self, r):
        r1, r2 = self, r
        if self.point.x > r.point.x or (self.point.x == r.point.x and self.point.y > r.point.y):
            r1, r2 = r, self
        if r1.bottom_right().x <= r2.point.x or r1.bottom_right().y <= r2.point.y:
            return None
        return Rectangle(r2.point,
            min(r1.bottom_right().x - r2.point.x, r2.width),
            min(r1.bottom_right().y - r2.point.y, r2.height))


r1 = Rectangle(Point(1, 1), 8, 5)
r2 = Rectangle(Point(2, 3), 9, 2)

print(r1, '\n', r1.surface_area(), '\n', r1.circunference(), '\n', r1.bottom_right())
r = r1.overlap(r2)
if r:
    print(r)
else:
    print('No, overlap.') 

我的问题在于 bottom_right 方法。我很确定它返回右上角,而不是右下角。但由于我仍然难以完全掌握这种连续性的逻辑,我担心我可能是错误的人。如果确实解决方案是正确的(该方法返回右下角的顶点),那么我缺少一些东西,因此我无法完全理解这段代码。

【问题讨论】:

    标签: python-3.x class oop object geometry


    【解决方案1】:

    你的程序中有很多隐含的假设...

    如果您在左上角用Pointwidthheight 定义Rectangle(以像素为单位),如果您使用的是笛卡尔坐标系,其中x 轴指向左侧,y 轴向上,您的bottom_right 方法将返回右上角的坐标。

    你可以改成:

    def bottom_right(self):
        return Point(self.point.x + self.width, self.point.y - self.height)
    

    【讨论】:

      【解决方案2】:

      这只是因为通常在计算机图形中,原点设置在左上角。因此,与您在数学几何中所习惯的相比,您实际上会有一个翻转的 y 轴。

      所以,你有这样的东西:

      因此,点(X, Y)实际上位于矩形的右下角,从点(0, 0)开始,宽度为X,高度为Y

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 2017-03-31
        • 2017-07-16
        相关资源
        最近更新 更多