Data Model Customization — ELI5
Imagine you build a robot toy. Out of the box, it can’t do much — it just sits there. But the toy comes with special slots where you can plug in different modules: a talking module, a walking module, a dancing module.
Python objects work the same way. Every object is like that toy, and Python has a set of special method slots you can fill in to give your object new powers.
The Magic Slots
Want your object to be added with +? Fill in the __add__ slot.
Want it to tell you how many items it has when you ask len()? Fill in the __len__ slot.
Want it to print something nice when you show it? Fill in the __repr__ slot.
These special methods (people call them “dunder methods” because they have double underscores around the name) are like a menu of abilities your object can learn.
An Everyday Example
Think about a shopping cart. You want to:
- Add items to it (
cart + item) - Count items (
len(cart)) - Check if something’s in it (
"milk" in cart) - Print it nicely (
print(cart))
A plain Python object can’t do any of that by default. But by filling in the right special methods, your shopping cart can understand all of those operations — just like Python’s own built-in lists and dictionaries.
Why This Is Cool
Most languages make you write separate named methods like cart.getLength() or cart.addItem(item). Python lets your objects “speak the same language” as built-in types. Your custom objects can use +, -, in, len(), for loops, and more — making them feel natural to use.
One thing to remember: Python’s data model lets you teach your objects to respond to operators and built-in functions by filling in special method slots.
See Also
- Python Attribute Lookup Chain How Python finds your variables and methods — like checking your pockets, then your bag, then your locker, in a specific order every time.
- Python Bytecode And Interpreter How your .py file turns into tiny instructions the Python interpreter can execute step by step.
- Python Class Body Execution Python runs the code inside your class definition immediately — like reading a recipe out loud before anyone starts cooking.
- Python Garbage Collection See how Python cleans up unreachable objects, especially the tricky ones that point at each other.
- Python Gil Why Python threads can feel stuck in traffic, and how the GIL explains the behavior.