0
0
Pythonprogramming~5 mins

String representation methods in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __str__ method in a Python class?
The __str__ method defines the "informal" or nicely printable string representation of an object. It is used by the print() function and str() to show a user-friendly description.
Click to reveal answer
beginner
What does the __repr__ method do in Python?
The __repr__ method returns an "official" string representation of an object. It is meant to be unambiguous and, if possible, match the code needed to recreate the object. Used by repr() and in the interactive interpreter.
Click to reveal answer
intermediate
If a class has both <code>__str__</code> and <code>__repr__</code> methods, which one does <code>print()</code> use?
print() uses the __str__ method if it is defined. If __str__ is missing, it falls back to __repr__.
Click to reveal answer
intermediate
Write a simple Python class Person with __str__ and __repr__ methods that show the person's name and age.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person named {self.name}, aged {self.age}"

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age!r})"
Click to reveal answer
intermediate
Why is it recommended that __repr__ returns a string that could be used to recreate the object?
Because __repr__ is mainly for developers, returning a string that can recreate the object helps debugging and testing. It shows the object's details clearly and can be used with eval() to make a copy.
Click to reveal answer
Which method is called by the print() function to get an object's string representation?
A__del__
B__repr__
C__init__
D__str__
What is the main difference between __str__ and __repr__?
A__str__ is for users; __repr__ is for developers
B__repr__ is for users; __str__ is for developers
CBoth are exactly the same
D__str__ is only for numbers
If a class defines only __repr__ but not __str__, what happens when you use print() on its object?
AIt prints nothing
BIt raises an error
CIt uses __repr__ output
DIt uses __init__ output
Which of these is a good practice for __repr__?
AReturn a string that can recreate the object
BReturn a short emoji
CReturn an empty string
DReturn a random number
What happens if neither __str__ nor __repr__ is defined in a class?
APython crashes
BPython shows a default string like <ClassName object at memory_address>
CPython prints None
DPython prints an empty line
Explain the difference between the __str__ and __repr__ methods in Python classes.
Think about who sees the output: users or developers.
You got /4 concepts.
    Write a Python class with both __str__ and __repr__ methods and describe what each returns.
    Use a simple example like a Person with name and age.
    You got /3 concepts.