Python Dunder Methods
A special method is how the badge itself answers a familiar action. You store the name mira on a Badge, and you do not install a package or create a folder. In the first program, print(guest) writes badge mira. That line runs str. You do not write guest.str() yourself. init still runs when you write Badge("mira"), and self is that badge. The words come back from str, and print is what puts them on the screen. There is one space between badge and mira.
class Badge:
def __init__(self, name):
self.name = name
def __str__(self):
return "badge " + self.name
guest = Badge("mira")
print(guest)
The screen shows one line: badge mira. The stored name is mira, and the front word badge is added by str. print writes that line. If this program had no print, the screen would stay empty, because returning the words is not the same as writing them. guest.str() is not in the program. print(guest) is enough to run that special method. A badge with no str would not write badge mira. The line would name the pattern and a place in memory. None is not written.
class Badge:
def __init__(self, name):
self.name = name
def __len__(self):
return len(self.name)
guest = Badge("mira")
print(len(guest))
The second program is separate. Its screen is the integer 4, not badge mira and not mira. mira has four letters, so len returns 4, and print writes 4. There is no decimal point. The stored name has no space in it. This program does not define str, so it does not try to write badge mira. If len were missing, len(guest) would stop. The name of that stop is TypeError. None is not written, and the program does not go on. That failing line is not in the program.
📊 What you write and what appears
| What you write | What the screen shows |
|---|---|
| print(guest) | badge mira |
| print(len(guest)) | 4 |
| len(guest) with no __len__ | the program stops |
The next page puts an object inside another object. This page only shows two special methods on one badge named mira.
Two answers from one badge
print(guest) writes badge mira, because str runs. print(len(guest)) writes 4, because len runs. 4 is how many letters mira has. You do not add parentheses after those special names. The next page puts an object inside another object.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top