我有一个名为Rectangle
的类,其中包含矩形位置,宽度和高度的方法,我想编写一个__str__
方法,可以很好地打印出这些信息。我已经对我的Point
类做了类似的事情并且它运行得很好,但我想这次它打印出方法的内存位置而不是转换为字符串的信息。
这是我的Point
类,包含在此处,因为需要创建一个Rectangle
对象:
class Point:
def __init__(self,initx,inity):
self.x = initx
self.y = inity
def getx(self):
return self.x
def gety(self):
return self.y
def __str__(self):
return 'x=' + str(self.x) + ', y=' + str(self.y)
这是Rectangle
:
class Rectangle:
def __init__(self,lowerleft,awidth,aheight):
self.location = lowerleft
self.width = awidth
self.height = aheight
def get_width(self):
return self.width
def get_height(self):
return self.height
def get_location(self):
return self.location
def __str__(self):
return 'Location: ' + str(self.location) + ', width: ' + str(self.get_width) + ', height: ' + str(self.get_height)
这是行print(my_rectangle)
的输出:
Location: x=4, y=5, width: <bound method Rectangle.get_width of <__main__.Rectangle object at 0x1006c4190>>, height: <bound method Rectangle.get_height of <__main__.Rectangle object at 0x1006c4190>>
print(my_rectangle.get_width())
,print(my_rectangle.get_height())
和print(my_rectangle.get_location())
完全符合预期。
提前致谢!
答案 0 :(得分:4)
您必须实际调用您的成员方法:
return 'Location: ' + str(self.location) + ', width: ' + str(self.get_width()) + ', height: ' + str(self.get_height())
Nota bene the parentheses。