Python Day #19: Python Dunder Methods Explained Simply
Learn Python dunder methods like __init__, __str__, and __len__. Master object-oriented programming with clear examples and practical use cases.
You’ve been following along my Python Roadmap to Success, recently we’ve just covered the four pillars of object-oriented programming.
These four pillars are in order for how you should learn them. These are: Encapsulation, Inheritance, Polymorphism, and Abstraction. These help us write cleaner, smarter programs in Python.
Today, I want to shift gears just a little and talk about something I did not introduce in these four pillars, that was intentional as I want us focusing on the core concepts at hand. But you’ve made it this far, so it’s time!
Every week you’ll be introduced to a new topic in Python, think of this as a mini starter course to get you going and allow you to have a structured roadmap that actually builds to create you a solid foundation in Python. Join us today!
In this lesson, I am going to cover Dunder methods. These are basically “magical functions” in a sense for working with classes. The term dunder comes from the meaning: double underscore methods.
These are the special methods in Python that start and end with two underscores. Which at this point you already have been using one for OOP as we’ve built out classes over the last four lessons, you’ve used __init__ countless times!
At first glance, they can look intimidating, especially if you have not been using them much. But once you understand them, they’re not only approachable, they’re downright powerful.
Over the last 8+ years I’ve been teaching full-time around the world which has given me the unique opportunity to work with over 1,500+ students. The last four years I’ve been teaching Python full-time. Breaking down complex topics, step by step.
I’ve spent this time curating a structured learning path that ensures my students have the greatest chance of success and don’t just learn but actually master Python as well as their logical thinking and problem solving.
This is The Python Roadmap to Success!
One point I should note is, spend time digesting these when I write them, after six weeks most of my posts are automatically put behind a paywall.
If you haven’t subscribed to my premium content yet, you should definitely check it out. You unlock exclusive access to all of these articles and all the code that comes with them, so you can follow along!
Plus, you’ll get access to so much more, like monthly Python projects, in-depth weekly articles, the 3 Randoms' series, and my complete archive!
I spend a lot of my week on these articles, so if you find it valuable, consider joining premium. It really helps me keep going and lets me know you’re getting something out of my work!
Thank you for allowing me to do work that I find meaningful. This is my full-time job so I hope you will support my work by joining as a premium reader today.
If you’re already a premium reader, thank you from the bottom of my heart! You can leave feedback and recommend topics and projects at the bottom of all my articles.
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
Each week’s lesson is designed to build directly on the last, giving you the tools and logical thinking skills you need to create a solid programming foundation.
What Are Dunder Methods?
Think of dunder methods as Python’s secret way of letting you customize how your objects behave. They’re hooks into the language itself. Ususally without them we can’t work with objects directly like we could with other variables in Python.
For example if we tried to just print off an object, we get a termianl output that looks something along the lines of: <__main__.Class object at 0x7f3a1c2b7d30>
Pretty much, that is useful to use in no way whatsoever. So we need a way to interact with objects on a basic level with Python just like we can with everything else in our scripts.
For instance if we want our class to work with len()
we can use __len__
. Or maybe we want to print something meaningful when we run print(my_obj)
. So instead of getting a. meaningless line back we can use __str__
to do this for us.
Python is already full of these behaviors for its built-in types (strings, lists, dictionaries). Dunder methods let us bring that same useful functionality into our own classes.
There are countless dunder methods from: __add__
, __sub__
, __enter__
, __exit__
, __lt__
, __gt__
, __delete__
. The list goes on and on, but in this lesson I want to cover the most commonly used ones.
Once you grasp how these play into our code, picking up new ones will feel like a breeze.
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
The Top 5 Most Commonly Used
There are a lot of dunder methods in Python, but you’ll find yourself coming back to the same handful over and over again. Let me break down the five most commonly used ones.
One thing to point out here, is these are useful as they all “call themselves”. You never have to call them like you would a normal class method linked to an object, no. As soon as you create an object, these will call themselves as you need them.
You just need to use your object like you would any other variable in your code.
__init__
: The Constructor
This is the one you’ve already seen the most. It runs every time you create a new object, and it sets everything up. This is hands down our most common one we see and it’s needed most of the time we are setting up a class.
What’s the appeal? Well this is automatically called when we make an object to initialize (set up) our class and is often the home to all of our class properties.
We can think of creating an object like moving into a new house, __init__
is the process of putting furniture inside so the house is livable. We are passing in outside information from the object, into the class through __init__ to get everything ready to “live in.”
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
__str__
: Human-Readable String
We can add in the ability to actually print off an object. Becasue when we do this we want something readable to us and natively we can not just print an object off.
If we print off an object we would normally get something like: <__main__.Class object at 0x7f3a1c2b7d30>.
But when we introduce the __str__ method then the whole game changes.
Without __str__
, printing an object just gives you a cryptic memory address. With it, you control what gets displayed. So when I try to print off my passenger object above this time it will actually return to me the string I want with the output in this case of:
Departing from Saigon with Air France!
Learn Python. Build Projects. Get Confident
Most people get stuck before they even start…
Wasted hours Googling, watching random YouTube videos, and never actually finish a project. But that doesn’t have to be you.
I’ve built The Python Masterclass to take you from “I don’t know where to start” to “I can build real-world Python projects” — in less than 90 days.
👉 I’m giving you my exact system that’s been proven and tested by over 1,500 students over the last 4+ years!
Here’s what you’ll get when you join today:
✅ All Course Videos — Learn Python without wasting time on scattered tutorials
✅ Python Templates & eBooks — Pre-built scripts, guides, and checklists
✅ How to Build a Portfolio - Mini Course — Learn the 5 step process ✅ Bi-monthly Live Q&A Calls (Pro/Elite) — Get answers in real time
✅ Portfolio/CV Reviews (Pro/Elite) — Tailored feedback to help you land work
✅ Personal Onboarding, Fast Support, & Custom Feedback (Elite) — I’ll personally guide to keep you moving
My masterclass is designed so you see your first win in less than 7 days — you’ll build your first working Python scripts in week one and finish projects in your first month.
The sooner you start, the sooner you’ll have projects you can actually show to employers or clients.
Imagine where you’ll be 90 days from now if you start today.
👉 Ready to get started?
P.S. — Get 20% off your First Month with the code: save20now
. Use it at checkout!
__repr__
: Developer-Friendly String
While __str__
is for humans, __repr__
is for developers. It’s what shows up when you type an object into the shell or use the Python repr()
function.
We use this more commonly in development so we don’t have to go around using print all the time, spamming up our codebase. We use this just through the terminal or using the repr()
function to tell apart from print()
.
So while __str__
is like a casual nickname you’d use in conversation, __repr__
is more like an official ID card. It’s precise, unambiguous, and mainly there to help you (or another developer) quickly understand what’s going on under the hood.
👉 I genuinely hope you get value from these articles, if you do, please help me out, leave it a ❤️, and share it with others who would enjoy this. Thank you so much!
__len__
: Length of an Object
You already know and use Python’s built-in len()
function all the time. You call len()
on a list and it tells you how many items are inside. You call it on a string and it tells you how many characters are in it.
But what if you make your own class and you want it to work the same way? That’s exactly what the __len__
method is for.
Think of __len__
as your way of teaching Python how to measure the size of your object. Without it, Python has no idea what len(my_object)
should mean.
Now the Airplane
class is holding onto a list of passengers. By adding __len__
, we’ve told Python: “If someone asks how long this airplane is, just tell them how many people are inside.”
So when we run len(airplane)
, it doesn’t blow up with an error—it works exactly like you’d expect, giving us back 4
.
__getitem__
: Indexing an Object
Normally, when you think of lists in Python, you just grab something with square brackets. This is what we call indexing. It looks like this:
That works because lists already know how to handle those brackets. But if you create your own class, it doesn’t magically know how to do that. Python is dumb… It’s up to us to tell it how to act.
That’s where __getitem__
comes in. It basically teaches your object how to respond when someone writes thing[0]
or thing["key"]
.
Now let’s load this plane up with some very “special” passengers:
See what happened? Without __getitem__
, trying airplane[0]
would have crashed, pun intended. But because we defined it, Python knows, “Oh, this object is pretending to be like a list, so I’ll hand it over to __getitem__
.”
This trick is useful whenever you’re building your own custom containers, maybe a deck of cards, a playlist, or even your own kind of database. You get to decide how the square brackets should work.
Wrapping Up Lesson Nineteen
Dunder methods might look a little strange when you first see them, but they’re really just built-in shortcuts that let your classes act like real Python objects.
We walked through how __init__
sets things up when you make an object, how __str__
and __repr__
make it easier to actually see what’s inside, and how __len__
and __getitem__
let your custom classes work with things like len()
and square brackets.
The main takeaway is that dunder methods aren’t anything extra or complicated. They’re simply the way you tell Python, “Hey, treat my object the same way you treat strings, lists, or dictionaries.” Instead of writing everything from scratch, you can tap into what Python already knows how to do.
As your projects get bigger, don’t shy away from these. They’ll save you time, make your code cleaner, and help it feel more natural to work with.
So the next time you write a class, ask yourself: “What should happen if someone prints it, measures it, or tries to index into it?” More often than not, there’s already a dunder method that handles exactly that.
Let’s keep moving forward with Day #20 next week.
Hope you all have an amazing week nerds ~ Josh (Chief Nerd Officer 🤓)
👉 If you’ve been enjoying these lessons, consider subscribing to the premium version. You’ll get full access to all my past and future articles, all the code examples, extra Python projects, and more.