__str__ and __repr__
The special methods that give an object its readable form and its developer form.
In more detail
print(), str() and f-strings use __str__; repr(), the interactive prompt and the display of objects inside a list use __repr__. The default repr shows the class name and a memory address. If a class defines only __repr__, str() falls back to it.
Example
class M:
def __str__(self): return 'm'
def __repr__(self): return 'M()'
print(M(), [M()]) # m [M()]Related terms
- dunder method — A method whose name starts and ends with two underscores, such as __init__ or __len__, which Python calls for you to implement built-in behaviour.
- class — A blueprint in code that bundles data and the functions that work on it, from which objects are made.
- print() — The built-in function that writes values to the screen, separated by spaces and followed by a newline.
Taught in
- Handlers, args, raise And assert — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exception Classes Of Your Own — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exceptions Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Characters As Numbers — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comparing, Slicing And Never Changing — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Strings Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Special Methods: __str__, __eq__ And Friends — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Streams, Handles And Open Modes — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- read, readline, errno And bytearray — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Mock, Review And Exam Day — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep