Hi there,
at university i have to program OO-style in Python. What i got now is a "Point"-class and a "Triangle"-class. The "Triangle"-class has a method a()
that needs to return the length of the AB-edge, but it doesn't instead it concatenates the Point.__str__() methods return values together, which is exactly what i dont want. It should instead add A.self.x, A.self.y to B.self.x, B.self.y, but this is syntactically incorrect in Python. TestDrive
looks like this:
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x)+ ", " + str(self.y) + ")"
def __add__(self, other):
total_x = other.x + self.x
total_y = other.y + self.y
return total_x, total_y
class Triangle(object):
def __init__(self, A=Point(), B=Point(), C=Point()):
self.A = A
self.B = B
self.C = C
#omitted Triangle.__str__
def a(self):
A = self.A
B = self.B
a_b_length = A.__add__(B)
return a_b_length
def main():
point_one = Point(3,5)
point_two = Point(7,11)
point_three = Point(6,13)
print("A ---> "+str(point_one))
print("B ---> "+str(point_two))
print("__add__ ---> "+str(point_one.__add__(point_two)))
print("__sub__ ---> "+str(point_two.__sub__(point_one)))
print("__neg__ ---> "+str(point_one.__neg__()))
print("__neg__ ---> "+str(point_two.__neg__()))
triangle_one = Triangle(point_one, point_two, point_three)
print("triangle ---> \n"+str(triangle_one))
print("triangle AB ---> "+triangle_one.a())
if __name__ == "__main__":
main()
if we look at line 88 - 100, the main method is as follows:
def main():
point_one = Point(3,5)
point_two = Point(7,11)
point_three = Point(6,13)
print("A ---> "+str(point_one))
print("B ---> "+str(point_two))
print("__add__ ---> "+str(point_one.__add__(point_two)))
print("__sub__ ---> "+str(point_two.__sub__(point_one)))
print("__neg__ ---> "+str(point_one.__neg__()))
print("__neg__ ---> "+str(point_two.__neg__()))
triangle_one = Triangle(point_one, point_two, point_three)
print("triangle ---> \n"+str(triangle_one))
print("triangle AB ---> "+triangle_one.a())
Here, every line just works the way i want, except for line 13
which should return the arguments x,y coordinates added(both of type Point()), but Python doesn't. (This particular self-casting is what i hate about Python by the way, str or int you dont know, you can do anything, but can't concatenate an int to a str in a print, ridiculous) print("triangle AB ---> "+triangle_one.a())
prints out triangle AB ---> (3, 5)(7, 11)
.
It should print triangle AB ---> (10,16)
instead, similar to line 7 in main
when adding single points together.
Has someone got an answer for this?