[英]Need help trying to test function to find area of rectangle using co-ordinates
[英]Trying out a test function for rectangle and coordinate classes to find area of the rectangle
我有2节课。 “矩形”和“坐标”找出两个坐标 tl(左上角)和 br(右下角)之间的差异,然后使用它们来找到矩形的面积。
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
class Coordinate: # coordinate class
def __init__(self,x,y):
# make coordinate obj with a reference (self), an x and a y
self.x=x
self.y=y
def distance(self,another): # distance between 2 coordinates
import math
xdist=abs(self.x-another.x)
ydist=abs(self.y-another.y)
return math.sqrt(xdist**2+ydist**2)
到目前为止,我已经把它写成一个测试函数来找出一个矩形的区域,它导致一个 AttributeError: 'int' object has no attribute 'x'
def test_function():
print("Testing Function")
tl = Coordinate(3,10)
br = Coordinate.distance(15,14)
rect = Rectangle(tl,br)
actual = rect.area()
print("Expected Area is 12 * 4 = 48")
print("Actual Result %d" % actual)
我可以更改 test_function 代码以使其工作吗?
def distance(self,another)
您需要从一个对象调用 this,并将另一个对象作为参数传递。 喜欢
tl = Coordinate(3,10)
br = tl.distance(Coordinate(15,14))
尽管在您的代码中,看起来tl
和br
应该是矩形的坐标,因此您应该将它们声明为
tl = Coordinate(3,10)
br = Coordinate(15,14)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.