OOP – String Representation (__str__), online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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
What students will learn in this module
Every question in Module 52
Quick questions
- What does __str__ control?AHow to create an objectBWhat print(object) displays
- When is __str__ called?AWhen you print() or str() the objectBWhen you create the object
- What must __str__ return?AA stringBNone
- What does print(obj) show without __str__?ANothingBSomething like <ClassName object at 0x...>
- 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 42Match it to what it doesdef Str(self):Match it to what it doesdef __str__(self):Match it to what it doesreturn f'Dog: {self.name}'Match it to what it doesstr(3.14)Match it to what it doesstr([1, 2])Match it to what it doesFill in the blanks
class Dog: def _______(self): return 'Dog: ' + self.nameclass Dog: def _______(self): ______ self.nameclass Dog: def __str__(self): return 'Dog: ' + ____.namedog = Dog('Rex') _____(dog)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'
