Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Python

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'}
Name mangling: inside class Secret, self.__hidden is rewritten to self._Secret__hidden, which is the only key stored on the object you write, inside the class self.__hidden Python stores self._Secret__hidden rename From outside, s.__hidden fails, but s._Secret__hidden works. It is a rename, not a lock.
Two leading underscores inside a class get the class name put in front.

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.

What Python calls for each operation: print(b) calls __str__, a == b calls __eq__, v1 + v2 calls __add__, len(p) calls __len__, p[0] calls __getitem__, for and in call __iter__, double(5) calls __call__ print(b) b.__str__() a == b, b < a __eq__, __lt__ v1 + v2 v1.__add__(v2) len(p) p.__len__() p[0] p.__getitem__(0) for song in p, "Sun" in p p.__iter__() double(5) double.__call__(5)
The switch you press, and the method Python calls behind it.

__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 writeWhat it means
namepublic
_namea sign for other developers; nothing stops access
__namerenamed 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 22 of 48

Previous
Python Multiple Inheritance, the MRO and Mixins
Next post
Python Composition, Abstract Classes and Dataclasses

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.

On this page

  • What encapsulation means
  • Python uses names, not locks
  • Name mangling is a rename
  • The trap: assigning from outside
  • The good pattern: private name, property, checking method
  • Special methods: the switches behind Python
  • __str__ and __repr__: what print shows
  • Comparing objects: __eq__ and __lt__
  • The plus sign: __add__
  • Acting like a list: __len__, __getitem__, __iter__
  • __bool__ falls back on __len__, and __call__
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.