我有一个简单的代码来创建一个矩形
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Rectangle:
def __init__(self, posn, w, h):
self.corner = posn
self.width = w
self.height = h
def __str__(self):
return "({0},{1},{2})".format(self.corner, self.width, self.height)
box = Rectangle(Point(0, 0), 100, 200)
print("box: ", box)
此代码的输出是
('box: ', <__main__.Rectangle instance at 0x0000000002368108>)
我希望输出是
box: ((0, 0), 100, 200)
有人能帮忙吗?你知道吗
您需要在这两个类中定义
__repr__
,如下所示似乎您正在使用python2.x:在python2.x中,^{} is statement, not a function 。你知道吗
通过放置
(...)
,您正在打印str(("box:", box))
。(包含字符串和Rectangle
对象的元组)去掉括号,定义
Point.__str__
以得到您所期望的结果。你知道吗输出:
您没有在
Rectangle
类上定义__repr__()
。打印元组(正如您所做的)使用类的repr()
,而不是str()
。在Point
类上还需要一个__str__()
。你知道吗相关问题 更多 >
编程相关推荐