[英]__str__ method called on return values of instance methods
我正在開發一個畫線並找到其中點的模塊。 為了進行測試,我想從相關類中創建一些字符串輸出。
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)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.