Python 需要帮助尝试测试函数以使用坐标找到矩形区域吗
我有一个矩形类,它使用左上角和右下角坐标查找矩形的面积。我在编写测试函数来测试代码并验证其工作时遇到问题Python 需要帮助尝试测试函数以使用坐标找到矩形区域吗,python,function,testing,area,Python,Function,Testing,Area,我有一个矩形类,它使用左上角和右下角坐标查找矩形的面积。我在编写测试函数来测试代码并验证其工作时遇到问题 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-b
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”对象没有属性“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
如果使用x
和y
表示元组的第一个和第二个元素tl
和br
,则应使用索引。元组没有这样的属性
如果使用
x
和y
表示元组的第一个和第二个元素tl
和br
,则应使用索引。元组没有这样的属性。一种简单的方法是将tl
和br
定义为字典而不是对象。这里有一个例子
类矩形:#矩形类
“”“使用左上角和右下角坐标制作矩形。”“”
定义初始值(self、tl、br):
self.width=abs(tl[“x”]-br[“x”])
self.height=abs(tl[“y”]-br[“y”])
def区域(自身):
返回自宽*自高
def test_矩形()
打印(“测试矩形类”)
tl={“x”:3,“y”:10}
br={“x”:4,“y”:8}
矩形=矩形(tl,br)
实际值=矩形面积()
打印(“结果为%d”%actual)
如果名称=“\uuuuu main\uuuuuuuu”:
测试_矩形()
一种简单的方法是将tl
和br
定义为字典,而不是对象。这里有一个例子
类矩形:#矩形类
“”“使用左上角和右下角坐标制作矩形。”“”
定义初始值(self、tl、br):
self.width=abs(tl[“x”]-br[“x”])
self.height=abs(tl[“y”]-br[“y”])
def区域(自身):
返回自宽*自高
def test_矩形()
打印(“测试矩形类”)
tl={“x”:3,“y”:10}
br={“x”:4,“y”:8}
矩形=矩形(tl,br)
实际值=矩形面积()
打印(“结果为%d”%actual)
如果名称=“\uuuuu main\uuuuuuuu”:
测试_矩形()
看起来tl和br是没有x属性的元组。你可以改为tl[0]
和tl[1]
吗?谢谢,@Fabich,代码已经整理好了。看起来tl和br是没有x属性的元组。你能改为tl[0]
和tl[1]
吗?谢谢,@Fabich,代码已经整理好了。