OOP – String Representation (__str__), online

Six activities your students do on their own devices. See who's finished, and their scores.

OOP – String Representation (__str__) in one minute

What students need to know

Python calls __str__ when you use print(obj) or str(obj). __str__ must return a string — f-strings work well here.

__str__ defines the human-readable string for the object — used by print(). print(obj) and str(obj) both trigger __str__ automatically.

Mistakes students make

  • __str__ must RETURN a string, not print it.
  • __str__ must return a string, not an integer.
  • Missing self parameter.
  • Need double underscores: __str__ not _str_.
PREVIOUS · MODULE 51OOP – Methods
YOU ARE HERE · MODULE 52OOP – String Representation (__str__)
NEXT · MODULE 53OOP – Practical Application

Discover other journeys with this module

What students will learn in this module

Every question in Module 52

Quick questions

  1. What does __str__ control?AHow to create an objectBWhat print(object) displays
  2. When is __str__ called?AWhen you print() or str() the objectBWhen you create the object
  3. What must __str__ return?AA stringBNone
  4. What does print(obj) show without __str__?ANothingBSomething like <ClassName object at 0x...>
  5. Does __str__ change the object?ANo it just returns a string descriptionBYes

Key terms

Students type the meaning of:

  • __str__(self)
  • __repr__(self)
  • print(object)
  • str(object)

Match the pairs

def __str__(self):
    return 42
Match it to what it does
def Str(self):Match it to what it does
def __str__(self):Match it to what it does
return f'Dog: {self.name}'Match it to what it does
str(3.14)Match it to what it does
str([1, 2])Match it to what it does

Fill in the blanks

  1. class Dog:
        def _______(self):
            return 'Dog: ' + self.name
  2. class Dog:
        def _______(self):
            ______ self.name
  3. class Dog:
        def __str__(self):
            return 'Dog: ' + ____.name
  4. dog = Dog('Rex')
    _____(dog)
  5. class Point:
        def _______(self):
            return '(' + str(____.x) + ')'

Spot the error

Question 1

Aclass Dog:B    def __str__(self):C        print('Dog: ' + self.name)

Question 2

Aclass Dog:B    def __str__(self):C        return 42

Question 3

Aclass Dog:B    def __str__():C        return 'Dog'

Question 4

Aclass Dog:B    def _str_(self):C        return 'Dog'

Question 5

Aclass Dog:B    def str(self):C        return 'Dog'