class Person:
def __init__(self, person_name, person_age):
self.name = person_name
self.age = person_age
def __str__(self):
return f'Person name is {self.name} and age is {self.age}'
def __repr__(self):
return f'Person(name={self.name}, age={self.age})'
p = Person('Pankaj', 34)
print(p.__str__())
print(p.__repr__())
Output:
Person name is Pankaj and age is 34
Person(name=Pankaj, age=34)
# When To Use __repr__ vs __str__?
# Emulate what the std lib does:
import datetime
today = datetime.date.today()
# Result of __str__ should be readable:
print(str(today))
# Output
# '2017-02-02'
# Result of __repr__ should be unambiguous:
print(repr(today))
# Output
# 'datetime.date(2017, 2, 2)'
# Python interpreter sessions use
# __repr__ to inspect objects:
print(today)
# Output
# datetime.date(2017, 2, 2)