Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
Python has no private keyword: one underscore is a sign, two underscores is a rename, and nothing is locked. Then the dunder methods that let print, ==, +, len, [] and for work on your own Book, Song, Vector and Playlist objects.
What you will learn
- Explain what one and two leading underscores mean, and what name mangling really does
- Protect an object's data with a private name, a property and a checking method
- Write __str__ and __repr__ so print shows something useful
- Make your own objects work with ==, <, +, len, [], in, for and calls
Before you start
- Python classes, objects and self
- Properties with @property
This article covers two ideas that make your classes feel like a natural part of Python. First, encapsulation: how a class looks after its data, and how Python really does that. Then special methods, the ones with double underscores, which let print, + and len work on your own objects.
What encapsulation means
A class keeps data and methods together. Encapsulation adds one more thought: the data stays inside, and outside code goes through the methods. When outside code wants to change something, it calls a method, and that method can check the value first. If code reaches in and changes the data directly, nothing checks it, and a bad value gets in. A small public front, with the details kept behind it.
Python uses names, not locks
Many languages have keywords like public and private. Python has none. It uses names. Think of an office:
- The reception is open to everyone. That's a normal name, called public.
- A door says "staff only". It isn't locked; you just respect the sign. That's one underscore, called protected.
- A room's number plate has been changed. Look for the old number and you won't find it. Use the new number and you walk right in. That's two underscores, which people call private.
There's no lock anywhere in this office.
class Employee:
def __init__(self, name, department, salary):
self.name = name
self._department = department
self.__salary = salary
emp = Employee("Priya", "Sales", 75000)
print(emp.name)
print(emp._department)
print(emp._Employee__salary)
Priya
Sales
75000
emp._department works, because one underscore is only a message to other developers. And the odd last line, emp._Employee__salary, reads the "private" value. Here's the case people usually show instead:
class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary
emp = Employee("Priya", 75000)
print(emp.name)
print(emp.__salary)
Priya
Traceback (most recent call last):
File "S03L05_Encapsulation\private_error.py", line 10, in <module>
print(emp.__salary)
^^^^^^^^^^^^
AttributeError: 'Employee' object has no attribute '__salary'
Notice it doesn't say "you aren't allowed". It says there's no such attribute. That's the clue: the value is there, under a different name.
Name mangling is a rename
class Secret:
def __init__(self):
self.__hidden = "classified"
def reveal(self):
return self.__hidden
s = Secret()
print(s.reveal())
print(s._Secret__hidden)
print(vars(s))
classified
classified
{'_Secret__hidden': 'classified'}
When Python reads the class and sees two leading underscores, it rewrites the name with _Secret in front. reveal is inside the class too, so its line is rewritten the same way and the names match. vars(s) shows the one key really stored. The point of this rename is so a child class doesn't overwrite your attribute by accident.
The trap: assigning from outside
class Employee:
def __init__(self, salary):
self.__salary = salary
def show(self):
return self.__salary
emp = Employee(75000)
emp.__salary = 1
print(emp.show())
print(emp.__salary)
emp._Employee__salary = 0
print(emp.show())
75000
1
0
There's no renaming outside a class, so emp.__salary = 1 makes a second, separate attribute. show still reads the renamed one, 75000. Then setting emp._Employee__salary to 0 changes the real value. Double underscores make accidents harder, but they don't keep anyone out. Don't treat them as security.
The good pattern: private name, property, checking method
class Account:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
self.__balance += amount
acc = Account(1000)
acc.deposit(250)
print(acc.balance)
1250
Reading goes through a property, so acc.balance needs no brackets. Changing goes through deposit, which checks the amount first. That's encapsulation in Python.
Special methods: the switches behind Python
Think of a wall switch. You press it and the light comes on, and you never touch the wiring. print, + and len are switches like that. Behind each one, Python calls a method with a fixed name and double underscores on both sides. People call them dunder methods or magic methods; dunder just means double underscore. These names end in two underscores as well, so they aren't mangled.
__str__ and __repr__: what print shows
Without these, printing a Book gives a default text with its class and a memory address. That doesn't help anyone.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __repr__(self):
return (f"Book({self.title!r}, "
f"{self.author!r}, {self.pages})")
b = Book("Dune", "Frank Herbert", 412)
print(b)
print(repr(b))
print([b])
Dune by Frank Herbert
Book('Dune', 'Frank Herbert', 412)
[Book('Dune', 'Frank Herbert', 412)]
print(b) calls __str__. repr(b) calls __repr__; the !r adds the quotes, so it looks like the code that would build this object. Printing a list uses repr for each item, which is why that form shows inside the square brackets. __str__ is for the user and __repr__ is for the developer. If you only write one, write __repr__, because print falls back on it.
Comparing objects: __eq__ and __lt__
class Song:
def __init__(self, title, seconds):
self.title = title
self.seconds = seconds
def __eq__(self, other):
return self.title == other.title
def __lt__(self, other):
return self.seconds < other.seconds
def __repr__(self):
return f"Song({self.title!r}, {self.seconds})"
a = Song("Rain", 210)
b = Song("Rain", 180)
c = Song("Sun", 240)
print(a == b)
print(a is b)
print(b < a)
print(sorted([c, a, b]))
True
False
True
[Song('Rain', 180), Song('Rain', 210), Song('Sun', 240)]
a == b goes to __eq__ with a as self and b as other. You decide what equal means; here it's the title, so the length doesn't matter. a is b calls no method, and these are still two objects. Without __eq__, == would behave just like is. b < a goes to __lt__, and sorted uses that same less-than to put the list in order.
The plus sign: __add__
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 1)
print(v1 + v2)
print(v1.__add__(v2))
Vector(6, 4)
Vector(6, 4)
+ doesn't know what a Vector is, so Python turns v1 + v2 into v1.__add__(v2). The x values add to 6, the y values to 4, and a new Vector comes back. The second line writes the same call by hand. This is called operator overloading; minus goes to __sub__ and times to __mul__ the same way.
Acting like a list: __len__, __getitem__, __iter__
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs)
def __getitem__(self, index):
return self.songs[index]
def __iter__(self):
return iter(self.songs)
p = Playlist(["Rain", "Sun"])
print(len(p))
print(p[0])
print(p[-1])
print("Sun" in p)
for song in p:
print("Now playing:", song)
2
Rain
Sun
True
Now playing: Rain
Now playing: Sun
p[-1] works because we pass the index straight on to the list, and a list understands negative numbers. There's no __contains__, so for "Sun" in p Python calls __iter__ and checks each item until it finds a match. The for loop uses the same door. We wrote almost no logic; the class hands the job to the list inside.
__bool__ falls back on __len__, and __call__
class Basket:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, value):
return value * self.factor
print(bool(Basket([])), bool(Basket(["pen"])))
double = Multiplier(2)
print(double(5))
print(double(8))
False True
10
16
There's no __bool__, so Python falls back on __len__: an empty basket is False, one item is True. That's how an if can test your object. double is just an object, but double(5) goes to __call__. The object remembers its factor and you call it like a function.
Quick recap
| You write | What it means |
|---|---|
name | public |
_name | a sign for other developers; nothing stops access |
__name | renamed to _ClassName__name; not a lock |
__str__ / __repr__ | text for users / text for developers |
__eq__, __lt__ | ==, < and sorted |
__add__ | + |
__len__, __getitem__, __iter__ | len, [], for and in |
__call__ | call the object like a function |
Try it yourself
Add __sub__ to Vector. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
