32. Classes and dunders (double underscores)

Exploit dunders when doing object-oriented programming in Python. In particular, override the __str__ dunder to enable a printer friendly representation of the object.

32.1. Don’t do this

1class Student():
2    def __init__(self, first_name, last_name):
3        self.first_name = first_name
4        self.last_name = last_name
5
6student = Student('John', 'Doe')
7
8print(student)

32.2. Do this

 1class Student():
 2    def __init__(self, first_name, last_name):
 3        self.first_name = first_name
 4        self.last_name = last_name
 5
 6    def __str__(self):
 7        return f'{self.first_name} {self.last_name}'
 8
 9student = Student('John', 'Doe')
10
11print(student)