1

I have simple code that creates a rectangle

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)

The output of this code is

('box: ', <__main__.Rectangle instance at 0x0000000002368108>)

I expect the output to be

box: ((0, 0), 100, 200) 

Can someone please help?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
yungalig
  • 29
  • 2
  • 10
  • Check out [this](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) post on `repr` vs `str` – C.B. Feb 24 '14 at 16:49

3 Answers3

4

You don't define a __repr__() on your Rectangle class. Printing a tuple (as you are doing) uses the repr() of the class, not the str(). You also need a __str__() on your Point class.

kindall
  • 178,883
  • 35
  • 278
  • 309
1

You need to define __repr__ in both the Classes, like this

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)
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

It seems like you're using Python 2.x: In Python 2.x, print is statement, not a function.

By putting (...), you're printing str(("box:", box)). (A tuple containing a string and Rectangle object)

Remove parentheses, and define Point.__str__ to get what you expected.


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)`.

output:

('box: ', <__main__.Rectangle instance at 0x00000000027BC888>)
box:  ((0, 0),100,200)
falsetru
  • 357,413
  • 63
  • 732
  • 636