__str__
vs __repr__
class Point(object):
def __init__(self,x=0,y=0):
self.x_coord = x
self.y_coord = y
def translate(self,x=0,y=0):
self.x_coord += x
self.y_coord += y
def print_point(self):
print("({:d},{:d})".format(self.x_coord, self.y_coord))
my_point = Point(1,2)
my_point.print_point()
(1,2)
class Point(object):
def __init__(self,x=0,y=0):
self.x_coord = x
self.y_coord = y
def translate(self,x=0,y=0):
self.x_coord += x
self.y_coord += y
def __str__(self):
return "({:d},{:d})".format(self.x_coord, self.y_coord)
new_point = Point(2,3)
print(new_point)
(2,3)
__str__
vs __repr__
¶__str__
finds the informal (human readable) string__repr__
find the formal (official) stringimport datetime
now = datetime.datetime.now()
str(now)
'2020-11-10 10:31:19.554885'
repr(now)
'datetime.datetime(2020, 11, 10, 10, 31, 19, 554885)'
__str__
vs __repr__
¶str() | repr() |
---|---|
Make object readable | Required code that reproduces object |
Generate output for end user | Generate output for a developer |