我正在开发一个绘制线并找到中点的模块。出于测试目的,我想从相关类创建一些字符串输出。
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
预期输出:
line from [4, 5] to [0, 0]
[2.0, 2.5]
相反,我得到:
line from [4, 5] to [0, 0]
<bound method Line.midpoint of <__main__.Line instance of 0x105064e18>>
如何获得中点的预期字符串表示形式,它作为 Point 类的实例返回?
最佳答案
您打印的是方法本身,而不是方法的返回值。将您的最后一行更改为:
print line1.midpoint()
此外,您的方法的第一行定义应使用 self 作为唯一参数,如下所示:
def midpoint(self):
这同样适用于其余的方法,它们应该以 self 作为参数(Point.getX 和 Point.getY)。
关于python - __str__ 方法调用实例方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41000223/