5

I have defined this class:

class Point():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __str__(self):
        return "Point x: {0}, Point y: {1}".format(self.x, self.y)

What is the difference between the 2 cases print("Point",p1) and print(p1):

p1 = Point(1,2)
print("Point",p1)
print(p1)

>>('Point', <__main__.Point instance at 0x00D96F80>)
>>Point x: 1, Point y: 2
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
user1050619
  • 19,822
  • 85
  • 237
  • 413

2 Answers2

12

The former is printing a tuple containing "Point" and p1; in this case __repr__() will be used to generate the string for output instead of __str__().

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    This would be different if it were on Python 3, though. Or if the "print_function" future is used .. see http://stackoverflow.com/questions/6182964/why-is-parenthesis-in-print-voluntary-in-python-2-7 –  Aug 18 '12 at 01:57
  • why should there be a difference in printing p1 when we have __str__() – user1050619 Aug 18 '12 at 01:57
  • 6
    Because sequences don't print the string value of their elements, they print the representation. – Ignacio Vazquez-Abrams Aug 18 '12 at 01:58
6

If you are using python2.x, then where you think you are calling print like a function, you are really printing a tuple, using the print keyword...

print(1,2,3)
print (1,2,3)

In python3, you have to do it like a function call print(1,2,3).

So in your case, in python2.x, what you are printing is a tuple of values. Tuple tuple object will be converted to a string, and each value in the tuple will have its representation printed. When you print them as this: print "Point",p1, then each item will be converted to a string and printed.

print str(p1)
# Point x: 1, Point y: 2

print repr(p1)
# <__main__.Point instance at 0x00D96F80>

You would actually probably want to use __repr__ instead of __str__:

class Point():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Point x: {0}, Point y: {1}".format(self.x, self.y)
jdi
  • 90,542
  • 19
  • 167
  • 203