String representation methods in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Let's explore how the time it takes to create string representations changes as the input grows.
We want to know how the work grows when we convert objects or data to strings.
Analyze the time complexity of the following code snippet.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
n = 10 # Example value for n
people = [Person(f"Name{i}", i) for i in range(n)]
for p in people:
print(str(p))
This code creates a list of people and prints their string representations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of people and calling
str()on each. - How many times: Exactly
ntimes, once for each person.
As the number of people grows, the total work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 string conversions |
| 100 | 100 string conversions |
| 1000 | 1000 string conversions |
Pattern observation: Doubling the number of people doubles the work.
Time Complexity: O(n)
This means the time to create all string representations grows directly with the number of items.
[X] Wrong: "Calling str() on each object is constant time overall because each call is fast."
[OK] Correct: Even if one call is fast, doing it n times adds up, so total time grows with n.
Understanding how string conversions scale helps you explain performance when working with lists or collections in real projects.
"What if the __str__ method included a loop over a list inside each object? How would the time complexity change?"
Practice
print() function?Solution
Step 1: Understand the purpose of __str__
The__str__method returns a readable string for users, used byprint().Step 2: Compare with __repr__
The__repr__method returns a detailed string for developers, not usually for printing.Final Answer:
__str__ -> Option CQuick Check:
Informal string for print() = __str__ [OK]
- Confusing __repr__ with __str__
- Thinking __init__ controls string output
- Assuming __del__ affects printing
__repr__ method inside a Python class?Solution
Step 1: Check method name and parameters
The method must be named__repr__and takeselfas parameter.Step 2: Verify return statement
__repr__must return a string, not print or use invalid syntax.Final Answer:
def __repr__(self): return 'object info' -> Option DQuick Check:
Correct __repr__ syntax returns string [OK]
- Omitting underscores in __repr__
- Using print instead of return
- Wrong method name without underscores
class Cat:
def __repr__(self):
return 'Cat()'
def __str__(self):
return 'A cute cat'
c = Cat()
print(c)
print(repr(c))Solution
Step 1: Understand print(c) calls __str__
Theprint(c)calls__str__, which returns 'A cute cat'.Step 2: Understand print(repr(c)) calls __repr__
Therepr(c)calls__repr__, which returns 'Cat()'.Final Answer:
A cute cat Cat() -> Option AQuick Check:
print() = __str__, repr() = __repr__ [OK]
- Mixing __str__ and __repr__ outputs
- Assuming print calls __repr__
- Confusing repr() with str()
class Dog:
def __str__(self):
return 'Dog'
def __repr__(self):
print('Dog object')
print(Dog())Solution
Step 1: Check __repr__ method body
The__repr__method usesprint()instead of returning a string, which is incorrect.Step 2: Understand consequences
Because__repr__returns None, printing the object calls__str__but repr() would fail to give a string.Final Answer:
__repr__ should return a string, not print it -> Option AQuick Check:
__repr__ must return string, not print [OK]
- Using print instead of return in __repr__
- Forgetting self parameter in methods
- Confusing print(Dog()) with print(Dog)
Book where print(book) shows the title nicely, but repr(book) shows a string that can recreate the object. Which implementation correctly achieves this?class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book titled '{self.title}'"
def __repr__(self):
# Which line below is correct?
passSolution
Step 1: Understand __str__ output
The__str__method returns a user-friendly string with the title.Step 2: Create __repr__ that recreates object
The__repr__should return a string that looks like the constructor call with a keyword argument and quotes around the title.Step 3: Check options for correct syntax
return f"Book(title='{self.title}')" returnsBook(title='title')which can be used to recreate the object. Others miss quotes or keyword.Final Answer:
return f"Book(title='{self.title}')" -> Option BQuick Check:
__repr__ returns constructor call string [OK]
- Missing quotes around string in __repr__
- Not using keyword argument in __repr__
- Returning informal string in __repr__
