Why does printing ("line", an object) give different results than printing (object)?

I 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 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
+5
source share
2 answers

The first prints a tuple containing "Point"and p1; in this case __repr__()will be used to generate a string for output instead __str__().

+12
source

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

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

In python3 you should do this as a function call print(1,2,3).

, , python2.x, , , . tuple tuple , . : print "Point",p1, .

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

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

, , __repr__ __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)
+6

All Articles