I am developing a module that draws lines and finds their midpoints. For purposes of testing, I want to create some string outputs from the relevant classes.
class Line:
def __init__(self, endpoints):
self.start = endpoints[0]
self.end = endpoints[1]
def midpoint():
x = (start.getX + end.getX) / 2.0
y = (start.getY + end.getY) / 2.0
return Point(x, y)
def __str__(self):
return "line from " + `self.start` + " to " + `self.end` + "."
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getX():
return x
def getY():
return y
def __str__(self):
return "[" + str(self.x) + ", " + str(self.y) + "]"
__repr__ = __str__
point1 = Point(4,5)
point2 = Point(0,0)
line1 = Line([point1, point2])
print line1
print line1.midpoint
Expected output:
line from [4, 5] to [0, 0]
[2.0, 2.5]
Instead I get:
line from [4, 5] to [0, 0]
<bound method Line.midpoint of <__main__.Line instance of 0x105064e18>>
How can I get the expected string representation of the midpoint, which is being returned as an instance of the Point class?
line1.midpoint, you're just referencing it. BTW, I thought that noone used the backticks in Python code anymore.reprso it would berepr(self.start)or you could use thestr(self.start). FYI: The backticks are removed in Python 3.repr(self.start)instead of the backticks or use:return 'line from {!r} to {!r}'.format(self.start, self.end)printas a statement is gone in Python 3 as well. Start addingfrom __future__ import print_functionto the top of your code and useprint()