Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can print("string", object) give different results than print(object)?

Tags:

python

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
like image 823
user1050619 Avatar asked Aug 18 '12 01:08

user1050619


1 Answers

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

like image 158
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 06:09

Ignacio Vazquez-Abrams