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

2 Answers 2

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__().

Sign up to request clarification or add additional context in comments.

3 Comments

This would be different if it were on Python 3, though. Or if the "print_function" future is used .. see stackoverflow.com/questions/6182964/…
why should there be a difference in printing p1 when we have __str__()
Because sequences don't print the string value of their elements, they print the representation.
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.