Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

When To Use __repr__ vs __str__?

# 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)
Source by www.journaldev.com #
 
PREVIOUS NEXT
Tagged: #When #To #Use
ADD COMMENT
Topic
Name
6+6 =