Implement __repr__ and __str__ on an Employee class so print() shows Employee(name='John', salary=50000). Learn which one Python calls when.
The problem
Make Employee(name, salary) print as:
Employee(name='John', salary=50000)
repr(employee)must return exactly that (note the quotes around the name — use!r)str(employee)returns"John earns 50000"
Examples
Example 1
Input
repr(Employee("John", 50000))Expected output
"Employee(name='John', salary=50000)"
Example 2
Input
str(Employee("John", 50000))Expected output
'John earns 50000'
+ 2 hidden tests on Submit — containers use repr, f-strings use str.
Edge cases to ask about
- Inside a list
- f-strings
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Two dunder methods | O(1) | O(1) | repr is for developers, str for users. |
Walkthrough of the optimal approach (try it yourself first)
__repr__ is for developers: unambiguous, ideally valid Python that recreates the object. __str__ is for end users. print() and f-strings use __str__; containers, the REPL and debuggers use __repr__. If only __repr__ exists, str() falls back to it.
@dataclass generates a correct __repr__ for free.
Complexity: O(1) time, O(1) space. String formatting of two fields.
Reveal the reference solution
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return f"Employee(name={self.name!r}, salary={self.salary!r})" def __str__(self): return f"{self.name} earns {self.salary}"
Follow-ups interviewers ask
- Rewrite it with @dataclass.
- What does !r do in an f-string?
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of __str__ vs __repr__ in Python?
The optimal solution runs in O(1) time and O(1) auxiliary space. String formatting of two fields.
What follow-up questions do interviewers ask about __str__ vs __repr__ in Python?
Rewrite it with @dataclass. What does !r do in an f-string?
