需要帮助尝试测试功能以使用坐标查找矩形区域

Need help trying to test function to find area of rectangle using co-ordinates

我有一个矩形 class,它使用左上角和右下角的坐标计算矩形的面积。我在编写测试函数来测试代码并验证其是否有效时遇到问题。

class Rectangle: # rectangle class
    # make rectangle using top left and bottom right coordinates
    def __init__(self,tl,br):
        self.tl=tl
        self.br=br
        self.width=abs(tl.x-br.x)  # width
        self.height=abs(tl.y-br.y) # height
    def area(self):
        return self.width*self.height

到目前为止,我已经写了导致 AttributeError: 'tuple' object has no attribute 'x'

def test_rectangle():
    print("Testing rectangle class")
    rect = Rectangle((3,10),(4,8))
    actual = rect.area()
    print("Result is %d" % actual)

我可以对代码进行哪些更改才能使其正常工作?

class Rectangle: # rectangle class
    # make rectangle using top left and bottom right coordinates
    def __init__(self,tl,br):
        self.tl=tl
        self.br=br
        self.width=abs(tl[0]-br[0])  # width
        self.height=abs(tl[1]-br[1]) # height
    def area(self):
        return self.width*self.height

如果 xy 是指元组的第一个和第二个元素 tlbr,则应改用索引。元组没有这样的属性。

一种简单的方法是将 tlbr 定义为字典而不是对象。这是一个例子。

class Rectangle:  # rectangle class
    """Make rectangle using top left and bottom right coordinates."""
    def __init__(self, tl, br):
        self.width = abs(tl["x"] - br["x"])
        self.height = abs(tl["y"] - br["y"])

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


def test_rectangle():
    print("Testing rectangle class")
    tl = {"x": 3, "y": 10}
    br = {"x": 4, "y": 8}
    rect = Rectangle(tl, br)
    actual = rect.area()
    print("Result is %d" % actual)


if __name__ == "__main__":
    test_rectangle()