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?✗ Incorrect
print() uses the __str__ method if available to show a user-friendly string.What is the main difference between
__str__ and __repr__?✗ Incorrect
__str__ gives a readable string for users; __repr__ gives a detailed string for developers.If a class defines only
__repr__ but not __str__, what happens when you use print() on its object?✗ Incorrect
If
__str__ is missing, print() falls back to __repr__.Which of these is a good practice for
__repr__?✗ Incorrect
__repr__ should return a string that looks like the code to recreate the object.What happens if neither
__str__ nor __repr__ is defined in a class?✗ Incorrect
Python uses a default representation showing the class name and memory address.
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.