SyntaxPilot
Courses/Python/Lesson 23

Python · Lesson 23 of 40 · 12 min

OOP 3: encapsulation, properties, dunder methods

queued

These are the notes for Python episode 23, the last part of our object oriented programming (OOP) trilogy. Our Customer class from episodes 21 and 22 works, but it has two weaknesses: anyone can put garbage into an object (a negative credit, a number stored as text), and our objects don't work with +, len(), in or == the way Python's own types do. In this episode we invent encapsulation, the _underscore convention and name mangling, properties with setters that validate data, read-only attributes, and dunder methods (__len__, __contains__, __add__, __getitem__, __eq__, __lt__, __repr__) that plug our classes into Python's built-in features. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: anyone can write anything

Raju's khata is an open book on the counter: anyone can pick up the pen. One helper types Asha's credit as -5000. Another reads Ravi's credit from input(), so it's the text "50", not a number.

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit

asha = Customer("Asha", 120)
asha.credit = -5000          # a typo at the counter
ravi = Customer("Ravi", 50)
ravi.credit = "50"           # read from input()

print(asha.name, "owes", asha.credit)
print("Total:", asha.credit + ravi.credit)

Output:

Asha owes -5000
Traceback (most recent call last):
  File "/tmp/tmp6h4_qzd3/main.py", line 12, in <module>
    print("Total:", asha.credit + ravi.credit)
                    ~~~~~~~~~~~~^~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The class happily accepted -5000, and the wrong type only crashes later, in the total.

Why it fails: every attribute is wide open. Any line of code anywhere can set it to anything, and the class never gets a chance to say no. The bug shows up far from the line that caused it.

What we want: the class guards its own data. Every change goes through a check.

Encapsulation: the bank teller's counter

At a bank In Python
The cash is behind glass; you can't reach in data is kept inside the object: self._credit
The teller takes your slip and checks it first every change goes through one door: a setter
You still just say "deposit 100" the outside stays simple: asha.credit += 30

Encapsulation means keeping an object's data inside it and letting the outside world change it only through the object's own code, where the rules live. Safe inside, simple outside.

Public, _internal and __mangled names

Python has no private keyword. It uses naming conventions:

Name Meaning
self.credit public: anyone may use it
self._credit internal: "please don't touch this from outside". Python doesn't stop you; it's a promise every Python developer respects
self.__credit name mangled: Python renames it to _Customer__credit behind the scenes

Name mangling in action:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.__credit = credit

asha = Customer("Asha", 120)
print(asha.__credit)

Output:

Traceback (most recent call last):
  File "/tmp/tmp2nkzv0yq/main.py", line 7, in <module>
    print(asha.__credit)
          ^^^^^^^^^^^^^
AttributeError: 'Customer' object has no attribute '__credit'

It looks hidden. But where did it go? Every object keeps its attributes in a dictionary called __dict__:

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.__credit = credit

asha = Customer("Asha", 120)
print(asha.__dict__)
print(asha._Customer__credit)

Output:

{'name': 'Asha', '_Customer__credit': 120}
120

Python just renamed it to _Customer__credit, and you can still reach it if you try. So Python has no truly private data. Name mangling exists mainly so that a child class can't clash with a parent's attribute by accident. For ordinary internal data, use a single underscore.

The clumsy fix: get_ and set_ methods

Many languages hide the attribute and add two methods:

asha.set_credit(asha.get_credit() + 30)
print(asha.get_credit())

It's safe, but clumsy, and every existing line like asha.credit += 30 would have to be rewritten.

@property: a method that looks like an attribute

A property looks exactly like a normal attribute from the outside, but reading it runs a getter method and assigning to it runs a setter method, where your check lives.

class Customer:
    def __init__(self, name, credit=0):
        self.name = name
        self.credit = credit       # goes through the setter

    @property
    def credit(self):
        return self._credit

    @credit.setter
    def credit(self, value):
        if not isinstance(value, int) or value < 0:
            raise ValueError(f"credit must be a whole number >= 0, got {value!r}")
        self._credit = value

asha = Customer("Asha", 120)
asha.credit += 30
print(asha.name, "owes", asha.credit)
asha.credit = -5000

Output:

Asha owes 150
Traceback (most recent call last):
  File "/tmp/tmp2zx0kauu/main.py", line 19, in <module>
    asha.credit = -5000
    ^^^^^^^^^^^
  File "/tmp/tmp2zx0kauu/main.py", line 13, in credit
    raise ValueError(f"credit must be a whole number >= 0, got {value!r}")
ValueError: credit must be a whole number >= 0, got -5000

How it works:

  • @property above def credit(self) makes asha.credit call this method. It returns the real value, stored in the internal self._credit.
  • @credit.setter above a second def credit(self, value) makes asha.credit = ... call it. It checks the value and only then stores it.
  • __init__ writes self.credit (no underscore), so even the first value goes through the check.
  • asha.credit += 30 reads (getter), adds, and writes (setter): the outside code didn't change at all.
  • {value!r} in the f-string shows the value with repr(), so a string appears with quotes, e.g. '50'.

The @ lines are decorators; you'll learn how they work in episode 25. For now, read @property as "the next method is a getter".

Read-only properties

A property with a getter and no setter is read-only:

class Customer:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

asha = Customer("Asha")
print(asha.name)
asha.name = "Ravi"

Output:

Asha
Traceback (most recent call last):
  File "/tmp/tmp1q2s2ze2/main.py", line 11, in <module>
    asha.name = "Ravi"
    ^^^^^^^^^
AttributeError: property 'name' of 'Customer' object has no setter

Perfect for values that must never change after creation: an account number, an order ID, a date of birth. Properties are also great for computed values, like total in the practice section.

Dunder methods: one socket, any plug

At home In Python
A wall socket works with any plug that fits built-ins like len(x), x + y, x == y are sockets
A plug with the right pins your class's dunder methods: __len__, __add__, __eq__
Plug in and it works, no rewiring len(cart) calls cart.__len__() for you

A dunder method ("double underscore", also called a magic or special method) is a method named __like_this__ that Python calls automatically. You already wrote two: __init__ and __str__.

Without the right pins, our own class doesn't plug in:

class Cart:
    def __init__(self, items):
        self.items = items

mine = Cart(["chai", "samosa"])
yours = Cart(["vada pav"])
print(mine + yours)

Output:

Traceback (most recent call last):
  File "/tmp/tmp4o2da7ki/main.py", line 7, in <module>
    print(mine + yours)
          ~~~~~^~~~~~~
TypeError: unsupported operand type(s) for +: 'Cart' and 'Cart'
class Cart:
    def __init__(self, items):
        self.items = items

mine = Cart(["chai", "samosa"])
print(len(mine))

Output:

Traceback (most recent call last):
  File "/tmp/tmpbgur1ckl/main.py", line 6, in <module>
    print(len(mine))
          ~~~^^^^^^
TypeError: object of type 'Cart' has no len()

Add the pins:

class Cart:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)

    def __contains__(self, item):
        return item in self.items

    def __add__(self, other):
        return Cart(self.items + other.items)

    def __str__(self):
        return "Cart: " + ", ".join(self.items)

mine = Cart(["chai", "samosa"])
yours = Cart(["vada pav"])
both = mine + yours
print(len(both))
print("samosa" in both)
print(both)

Output:

3
True
Cart: chai, samosa, vada pav
  • len(both) → both.__len__(); it must return a whole number ≥ 0.
  • "samosa" in both → both.__contains__("samosa"); return True or False.
  • mine + yours → mine.__add__(yours); return a new object, don't change the originals.

Giving an operator like + a meaning for your own class is called operator overloading.

__str__ vs __repr__, __eq__ and __lt__

Two surprises with a simple Rupees class:

class Rupees:
    def __init__(self, amount):
        self.amount = amount

    def __str__(self):
        return f"Rs {self.amount}"

a = Rupees(50)
b = Rupees(50)
print(a == b)
print([a, b])

Output:

False
[<__main__.Rupees object at 0x7fdecd0730e0>, <__main__.Rupees object at 0x7fdeccd7ccd0>]

(The 0x... numbers are memory addresses and differ on every run.)

  1. False: without __eq__, == only asks "is this the very same object?" These are two different objects.
  2. The list shows <... object at 0x...> even though we wrote __str__: a list prints its items with __repr__, not __str__.

The fix:

class Rupees:
    def __init__(self, amount):
        self.amount = amount

    def __str__(self):
        return f"Rs {self.amount}"

    def __repr__(self):
        return f"Rupees({self.amount})"

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount

a = Rupees(50)
b = Rupees(50)
print(a == b)
print([a, b])
print(sorted([Rupees(90), Rupees(20), Rupees(50)]))

Output:

True
[Rupees(50), Rupees(50)]
[Rupees(20), Rupees(50), Rupees(90)]
  • __repr__ is the developer-friendly text; a good one looks like the code that creates the object. Lists, dicts and the interactive console use it.
  • __str__ is the user-friendly text for print() and str(). If a class has only __repr__, print() uses that.
  • __eq__ defines ==. __lt__ ("less than") defines <, and that's all sorted(), min() and max() need.

The dunder cheat sheet

You write Python calls
len(x) x.__len__()
a + b a.__add__(b)
item in x x.__contains__(item)
x[key] x.__getitem__(key)
a == b a.__eq__(b)
a < b (and sorted, min, max) a.__lt__(b)
print(x), str(x) x.__str__()
repr(x), an item inside a list x.__repr__()
Customer("Asha") __init__ on the new object

Common mistakes

Mistake What you see Why Fix
ravi.credit = "50" then adding TypeError: unsupported operand type(s) for +: 'int' and 'str' nothing guarded the attribute a property with a validating setter
asha.__credit from outside AttributeError: 'Customer' object has no attribute '__credit' name mangling renamed it use _credit and a property
assigning to a getter-only property AttributeError: property 'name' of 'Customer' object has no setter it's read-only add @name.setter if it may change
storing the value as self.credit inside the setter RecursionError: maximum recursion depth exceeded the setter calls itself forever store it in self._credit
len(cart) TypeError: object of type 'Cart' has no len() no __len__ def __len__(self):
cart1 + cart2 TypeError: unsupported operand type(s) for +: 'Cart' and 'Cart' no __add__ def __add__(self, other):
Rupees(50) == Rupees(50) no error: False == checks identity without __eq__ def __eq__(self, other):
sorted(list_of_rupees) TypeError: '<' not supported between instances of 'Rupees' and 'Rupees' no __lt__ def __lt__(self, other):
a list prints <... object at 0x...> no error lists use __repr__ def __repr__(self):

The recursion trap, for the record:

class Customer:
    @property
    def credit(self):
        return self._credit

    @credit.setter
    def credit(self, value):
        self.credit = value    # should be self._credit

Customer().credit = 10

Output:

Traceback (most recent call last):
  File "/tmp/tmpc37b6hwf/main.py", line 10, in <module>
    Customer().credit = 10
    ^^^^^^^^^^^^^^^^^
  File "/tmp/tmpc37b6hwf/main.py", line 8, in credit
    self.credit = value    # should be self._credit
    ^^^^^^^^^^^
  File "/tmp/tmpc37b6hwf/main.py", line 8, in credit
    self.credit = value    # should be self._credit
    ^^^^^^^^^^^
  File "/tmp/tmpc37b6hwf/main.py", line 8, in credit
    self.credit = value    # should be self._credit
    ^^^^^^^^^^^
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Mini project: a Khata container class

A Khata keeps an internal dictionary _people (name → Customer) that outside code never touches directly. It takes any number of customers with *customers (episode 14). Three dunders make it feel like a built-in container: len(), in and square brackets.

class Customer:
    def __init__(self, name, credit=0):
        self.name, self.credit = name, credit

class Khata:
    def __init__(self, *customers):
        self._people = {c.name: c for c in customers}
    def __len__(self):
        return len(self._people)
    def __contains__(self, name):
        return name in self._people
    def __getitem__(self, name):
        return self._people[name]

khata = Khata(Customer("Asha", 120), Customer("Ravi", 50))
print(len(khata), "customers")
print("Asha" in khata, "Meena" in khata)
khata["Ravi"].credit += 25
print("Ravi owes", khata["Ravi"].credit)

Output:

2 customers
True False
Ravi owes 75

It reads like a dictionary, but it's our own class with our own rules inside.

Try it: add a read-only property total that returns the sum of everyone's credit (solution below).

Practice

1. Add a read-only total property to the Khata above.

Solution
class Customer:
    def __init__(self, name, credit=0):
        self.name, self.credit = name, credit

class Khata:
    def __init__(self):
        self._people = {}
    def add(self, c):
        self._people[c.name] = c
    @property
    def total(self):
        return sum(c.credit for c in self._people.values())

khata = Khata()
khata.add(Customer("Asha", 120))
khata.add(Customer("Ravi", 50))
print("Total credit:", khata.total)

Output:

Total credit: 170

2. A Temperature class with a celsius property whose setter rejects values below −273.15 with ValueError, and a read-only fahrenheit property.

Solution
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

t = Temperature(25)
print(t.celsius, t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)
t.celsius = -300

Output:

25 77.0
212.0
Traceback (most recent call last):
  File "/tmp/tmphxkwz9n1/main.py", line 23, in <module>
    t.celsius = -300
    ^^^^^^^^^
  File "/tmp/tmphxkwz9n1/main.py", line 12, in celsius
    raise ValueError("below absolute zero")
ValueError: below absolute zero

3. Make a Marks class (name and score) with __eq__, __lt__ and __repr__, then sort a list of them and print the highest with max().

Solution
class Marks:
    def __init__(self, name, score):
        self.name, self.score = name, score
    def __repr__(self):
        return f"Marks({self.name!r}, {self.score})"
    def __eq__(self, other):
        return self.score == other.score
    def __lt__(self, other):
        return self.score < other.score

students = [Marks("Asha", 91), Marks("Ravi", 78), Marks("Meena", 85)]
print(sorted(students))
print(max(students))
print(Marks("X", 80) == Marks("Y", 80))

Output:

[Marks('Ravi', 78), Marks('Meena', 85), Marks('Asha', 91)]
Marks('Asha', 91)
True

4. A Playlist class holding song names with __len__, __getitem__ (by position) and __add__. What happens if you loop over it with for?

Solution
class Playlist:
    def __init__(self, songs):
        self.songs = songs
    def __len__(self):
        return len(self.songs)
    def __getitem__(self, i):
        return self.songs[i]
    def __add__(self, other):
        return Playlist(self.songs + other.songs)

p = Playlist(["Song A", "Song B"]) + Playlist(["Song C"])
print(len(p), p[0], p[-1])
for song in p:
    print("Playing", song)

Output:

3 Song A Song C
Playing Song A
Playing Song B
Playing Song C

The for loop works too: when a class has no __iter__, Python falls back to calling __getitem__ with 0, 1, 2, ... until IndexError. Episode 24 shows how loops really work.

Quick quiz

1. The video's quiz: what does this print?

class Glass:
    def __init__(self, ml):
        self.ml = ml
    def __add__(self, other):
        return Glass(self.ml + other.ml)
    def __str__(self):
        return f"{self.ml} ml"

print(Glass(100) + Glass(150), Glass(100) == Glass(100))
Answer

Output:

250 ml False

__add__ makes a new 250 ml glass and __str__ prints it. There's no __eq__, so == asks if they're the same object: two different objects, False.

2. Which name does Python rename (mangle): self.total, self._total, self.__total, or self.__total__?

Answer

Only self.__total. Names with two leading underscores and two trailing underscores (dunders like __init__) are not mangled.

3. What does this print?

class P:
    def __repr__(self):
        return "R"

print(P(), [P()], str(P()))
Answer

Output:

R [R] R

With no __str__, print() and str() fall back to __repr__.

Interview questions

  1. What is encapsulation? Bundling data with the methods that operate on it, and restricting direct outside access so that every change goes through the object's own code, where invariants (rules) are enforced.
  2. Does Python have private attributes? No. _name is a convention for "internal"; __name triggers name mangling (_Class__name), which avoids accidental clashes in subclasses but doesn't truly hide anything.
  3. What is @property? A built-in decorator that turns a method into a managed attribute: reading the attribute calls the getter; with @x.setter and @x.deleter, assignment and del call methods too. It lets you add validation without changing the public interface.
  4. Why prefer properties over get_x()/set_x() in Python? You can start with a plain attribute and switch to a property later without changing any code that uses it, and the syntax stays clean.
  5. How do you make a read-only attribute? A property with only a getter (no setter); assigning to it raises AttributeError.
  6. What are dunder (magic) methods? Specially named methods (__len__, __add__, __eq__, ...) that Python calls to implement built-in functions, operators and syntax for your objects.
  7. __str__ vs __repr__? __str__ is the readable text for end users (print, str); __repr__ is the unambiguous developer text (console, containers, repr), ideally valid code to recreate the object. If only __repr__ exists, it is used for both.
  8. What happens to == if you don't define __eq__? It falls back to identity (is): two separate objects are never equal. Note: defining __eq__ sets __hash__ to None, so the objects can't be used in sets or as dict keys unless you also define __hash__.
  9. What does sorted() need from your objects? Only <, i.e. __lt__. (functools.total_ordering can fill in the other comparisons from __eq__ and one of them.)
  10. What is operator overloading? Defining what an operator like +, < or [] means for your own class by implementing the matching dunder method.

Glossary

Term Meaning Example
Encapsulation Keeping data inside an object and changing it only through the object's own code self._credit + a setter
Public attribute An attribute meant to be used from outside asha.name
_internal (single underscore) Convention: "internal, don't use from outside" self._credit
Name mangling Python renames __name to _ClassName__name asha._Customer__credit
__dict__ The dictionary holding an object's attributes {'name': 'Asha', ...}
Getter A method that returns a value @property def credit(self):
Setter A method that runs when a value is assigned @credit.setter
Property An attribute whose reads and writes run methods asha.credit += 30
@property The decorator that creates a property @property
Read-only property A property with no setter asha.name above
Validation Checking a value before accepting it if value < 0: raise ValueError
Invariant A rule that must always be true for an object credit is never negative
ValueError The right type but a bad value credit must be ... got -5000
repr() / !r The developer text of a value; strings get quotes f"{value!r}" → '50'
Dunder (magic, special) method A __name__ method Python calls for you __len__, __add__
__len__ Called by len() len(cart)
__contains__ Called by in "samosa" in cart
__add__ Called by + mine + yours
__getitem__ Called by square brackets khata["Ravi"]
__eq__ Called by == Rupees(50) == Rupees(50)
__lt__ Called by <; used by sorted, min, max sorted(amounts)
__repr__ Developer text; used inside lists and the console Rupees(50)
__str__ User text; used by print() Rs 50
Operator overloading Giving an operator a meaning for your class Cart + Cart
Identity Being the very same object (is) a is b
Container An object that holds other objects Khata, Cart, list
RecursionError A function calling itself with no end a setter assigning self.credit

Summary

  • Open attributes let anyone write anything; bad data crashes far from where it came in.
  • Encapsulation: the object guards its own data. _name means internal; __name is mangled to _Class__name; Python has no truly private data.
  • A property looks like an attribute but runs methods: @property (getter) and @x.setter (setter, with validation). Store the real value in self._x.
  • No setter = read-only.
  • Dunder methods plug objects into Python: __len__ (len), __contains__ (in), __add__ (+), __getitem__ ([]), __eq__ (==), __lt__ (<, sorted).
  • __str__ is for users, __repr__ for developers (and lists). Without __eq__, == checks identity.

Next episode: the shop's sales file has ten million lines, and reading it all into a list fills the memory. We invent iterators and generators, and see how a for loop really works.