在python学习类但有可能很简单的问题

时间:2014-02-24 16:43:58

标签: python class

我有一个简单的代码,可以创建一个矩形

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) 

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

您未在__repr__()课程中定义Rectangle。打印元组(正如您所做)使用类的repr(),而不是str()。您的__str__()课程还需要Point

答案 1 :(得分:1)

您需要在两个类中定义__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)

答案 2 :(得分:0)

好像你正在使用Python 2.x:在Python 2.x中,print 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)