问题描述
我有一个Rectangle类,该类使用左上角和右下角坐标找到Rectangle的区域。我在编写测试功能以测试代码并验证其工作时遇到麻烦。
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
的第一和第二个元素,则应改用索引。元组没有这样的属性。
一种简单的方法是将tl
和br
定义为字典而不是对象。这是一个例子。
class Rectangle: # rectangle class
"""Make rectangle using top left and bottom right coordinates."""
def __init__(self,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()