Classes & Objects · Question 18 · Hard

The Coin class defines both __str__ and __repr__. What is printed for the object itself and for a list holding it?

class Coin:
    def __str__(self):
        return "str"
    def __repr__(self):
        return "repr"

c = Coin()
print(c, [c])
  1. str [str]
  2. str [repr]
  3. repr [repr]
  4. repr [str]
Answer and explanation

Answer: B. str [repr]

Explanation: print uses __str__ for the object it is given directly. A list builds its own string by using __repr__ for each element, so the object inside the list shows as repr.

Previous: Every class in this diamond calls super().go(). What string does D().go() build? · Next: total is a property with only a getter. What happens when the code tries to…

Practise classes & objects

Try a fresh set of classes & objects questions with an explanation after every answer, free and without signing up: Classes & Objects practice. Or sit a full placement mock test.

More classes & objects questions

More python practice

Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge