Generally, when debugging a program, print is more inclined to use direct printing to make judgments, but print can only print out the results, and cannot judge the type. E.g:
Copy code
a = 5
b = ‘5’
print(a)
print(b)
The result is:
5
5
Copy code
For a and b are the same on the surface, it may default to a == b
In fact, a is of type int and b is of type string
Use repr to see the result:
Copy code
a = 5
b = ‘5’
print(repr(a))
print(repr(b))
The result is:
5
‘5’
Copy code
For dynamic python objects, it is also very convenient to use repr:
Copy code
class OpenClass(object):
def init(self, x, y):
self.x = x
self.y = y
obj = OpenClass(2,3)
print(obj)
Copy code
Rebuild the object with repr:
Copy code
class OpenClass(object):
def init(self, x, y):
self.x = x
self.y = y
def repr(self):
return ‘OpenClass(%d,%d)’%(self.x, self.y)
obj = OpenClass(2,3)
print(obj)
Copy code
For print, only easy-to-read information can be printed, but the type cannot be displayed
repr displays the type and concisely displays the data information
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts