学习python,但问题可能是simp

2024-04-26 11:43:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码来创建一个矩形

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) 

有人能帮忙吗?你知道吗


Tags: 代码selfboxreturninitdefwidthclass
3条回答

您需要在这两个类中定义__repr__,如下所示

class Point(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __repr__(self):
        return "({}, {})".format(self.x, self.y)

class Rectangle(object):
    def __init__(self, posn, w, h):
        self.corner = posn
        self.width = w
        self.height = h

    def __repr__(self):
        return "({0},{1},{2})".format(self.corner, self.width, self.height)

print "box: ", box
# box:  ((0, 0),100,200)

似乎您正在使用python2.x:在python2.x中,^{} is statement, not a function。你知道吗

通过放置(...),您正在打印str(("box:", box))。(包含字符串和Rectangle对象的元组)

去掉括号,定义Point.__str__以得到您所期望的结果。你知道吗


class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return str((self.x, self.y))
        # OR   return '({0.x}, {0.y})'.format(self)

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)  # This prints a tuple: `str(("box: ", box))`
print "box: ", box   # This prints `box: ` and `str(box)`.

输出:

('box: ', <__main__.Rectangle instance at 0x00000000027BC888>)
box:  ((0, 0),100,200)

您没有在Rectangle类上定义__repr__()。打印元组(正如您所做的)使用类的repr(),而不是str()。在Point类上还需要一个__str__()。你知道吗

相关问题 更多 >