Thuta Learning
Python
IntermediateProgrammingBeginner

Encapsulation (Enhanced)

PythonLesson 2425 min

What you'll walk away with

  • Explain how a public attribute lets an object fall into an invalid state
  • Tell _name (internal) from __name (name mangling) and explain why neither is security
  • Write read-only attributes and validating setters with @property
  • Replace get_x()/set_x() methods with Pythonic properties

Explain it simply

Explain it simply

Think of an ATM. You cannot reach into the bank's vault and grab cash; you go through the buttons: withdraw, deposit, check balance. Every button checks first whether the action is allowed, so you cannot withdraw more than you have.

Encapsulation turns a class into that ATM. The data, such as a balance, and the methods that change it, such as deposit and withdraw, live together in the class, and outside code changes the data only through checked buttons. The object then never ends up in a nonsense state such as a negative balance.

Problem → Why → Solution

The problem: anyone can rewrite the balance

In the class below, balance is a plain public attribute. withdraw() contains a check, but any line anywhere in the program can still write account.balance = -500. Python accepts it without an error, and every later interest calculation and report is wrong.

open_account.py
class BankAccount:
    def __init__(self, balance):
        self.balance = balance          # public, unprotected

    def withdraw(self, amount):
        if amount <= self.balance:      # the rule lives here...
            self.balance -= amount

account = BankAccount(1000)
account.balance = -500                  # ...but this skips the rule entirely
print(account.balance)                  # -500

Why is this dangerous?

The rule "balance is never negative", an invariant, can no longer be guarded by the object itself; every place in the codebase that touches the attribute has to behave. When a bug appears, you have to search the whole project to find who changed it. If every change goes through a method or a property, the check lives in exactly one place.

Core concept: conventions, name mangling and properties

In languages such as Java or C#, the private keyword truly blocks access, but in Python every attribute can be reached one way or another. Python's encapsulation rests on clear public interfaces and conventions rather than absolute privacy. The community sums it up as "we are all consenting adults here".

FormMeaning
namePublic: part of the interface; anyone may read and change it
_nameInternal: a "do not touch from outside" convention; Python does not block it
__nameName mangling: renamed to _ClassName__name to avoid clashes in subclasses

A single underscore, as in _balance, tells other developers "this is an implementation detail and may change in the next version". A double underscore, as in __pin, makes Python rewrite the attribute name to _BankAccount__pin; this is called name mangling. Its purpose is to stop a subclass from accidentally overriding an attribute with the same name, not security: obj._BankAccount__pin still reads it.

Real protection comes from public methods and properties. The @property decorator lets a method be read like an attribute: you write acct.balance without parentheses, but a function runs behind it. Without a setter the attribute is read-only and assigning to it raises AttributeError; with an @name.setter, every assignment runs your validation.

That is why Python code rarely needs get_balance()/set_balance() methods up front. Start with a plain public attribute, and if a check becomes necessary later, turn it into a property; callers' code such as obj.x = 5 does not change by a single line.

Properties are not only for validation; they also serve computed values. A Temperature that stores only celsius and calculates fahrenheit on every read can never have the two values drift out of sync. Because callers no longer depend on the internal representation, you can change how the data is stored later without breaking them.

Mental model: every change passes a gate
  1. Caller uses a method or property
  2. The gate checks the rule
  3. Valid: update the internal _data
  4. Invalid: raise, state stays unchanged

The underscore only says "keep out"; the checking gate is what actually protects.

General pattern

python
class Thing:
    def __init__(self, value):
        self.value = value             # runs the setter below

    @property
    def value(self):                   # read: obj.value
        return self._value

    @value.setter
    def value(self, new):              # write: obj.value = new
        # validate new, raise ValueError if it breaks a rule
        self._value = new

The real data lives in _value; @property is the reading gate and @value.setter the writing gate. __init__ also goes through the setter with self.value = value, so new objects are validated too. Leave out the setter for a read-only attribute.

Example: a protected BankAccount

The balance is stored in _balance, and the balance property, which has no setter, only allows reading. Money changes only through deposit() and withdraw(), and both check the rules. At the end the code tries twice to break them.

bank_account.py
class BankAccount:
    def __init__(self, owner, balance=0):
        if balance < 0:
            raise ValueError("opening balance cannot be negative")
        self.owner = owner           # public: free to read and change
        self._balance = balance      # internal: change it via methods

    @property
    def balance(self):               # read like an attribute
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

    def withdraw(self, amount):
        if not 0 < amount <= self._balance:
            raise ValueError(f"cannot withdraw {amount}")
        self._balance -= amount


acct = BankAccount("Sai", 1000)
acct.deposit(500)
acct.withdraw(200)
print(acct.owner, acct.balance)

try:
    acct.withdraw(5000)
except ValueError as e:
    print("blocked:", e)

try:
    acct.balance = -500          # no setter, so this is refused
except AttributeError:
    print("blocked: balance is read-only")

print(acct.balance)

Code breakdown

  1. Line 6self._balance = balance # internal: change it via methods

    One underscore is the "do not change this from outside" convention. Python will not stop anyone, but linters and code reviewers will flag it.

  2. Lines 8-10@property

    Lets callers read acct.balance without parentheses. There is no setter, so it is read-only.

  3. Line 18if not 0 < amount <= self._balance:

    A chained comparison: continue only if amount is above 0 and no more than the balance; otherwise raise ValueError and leave the balance untouched.

  4. Line 34acct.balance = -500 # no setter, so this is refused

    The same line that worked in the problem section. Now the property has no setter, so it raises AttributeError and the balance stays 1300.

You should see
Sai 1300
blocked: cannot withdraw 5000
blocked: balance is read-only
1300

Seeing name mangling in action

The name __code is actually stored on the object as _Vault__code. hasattr(v, "__code") therefore returns False, yet the value is still readable through the mangled name. Never assume a double underscore hides secrets such as passwords or API keys.

vault.py
class Vault:
    def __init__(self):
        self.__code = 1234           # name-mangled to _Vault__code

v = Vault()
print(hasattr(v, "__code"))          # False
print(v._Vault__code)                # 1234: still reachable, not security

Properties instead of get_name()/set_name()

Getter and setter methods such as get_name() and set_name() do work, but in Python a property is more natural. In the Person class below, p.name = "Aye" looks like a plain assignment, yet the setter trims spaces and rejects an empty name.

person_property.py
class Person:
    def __init__(self, name):
        self.name = name             # goes through the setter below

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

    @name.setter
    def name(self, value):
        value = value.strip()
        if not value:
            raise ValueError("name cannot be empty")
        self._name = value

p = Person("  Sai ")
p.name = "Aye"
print(p.name)                        # Aye
try:
    p.name = "   "
except ValueError as e:
    print(e)                         # name cannot be empty

In real projects

Where this shows up in real projects

In an e-commerce system, an Order's status must move only in the order pending, then paid, then shipped. If any code can write order.status = "shipped", an unpaid order might be sent out. A mark_shipped() method that only allows the change when the status is "paid" keeps that rule in a single place.

Encapsulation matters for library authors too. Names starting with _ are not public API, so they can change in the next version without breaking users' code. In pandas, a property such as df.shape exposes a computed value as if it were an attribute. Configuration objects often put validation in a setter, for example a port number must be between 1 and 65535, so a bad config stops the program at startup with a clear error.

Common mistakes

Common mistakes

1. Treating __name as security

self.__password feels safe, but obj._User__password still reads it and vars(obj) shows it. Store secrets hashed, keep them out of logs, and do not include them in __repr__.

2. A property that refers to itself

@property def name(self): return self.name calls the property again and again until RecursionError. Writing self.name = value inside the setter does the same. Store the real data under a different name such as self._name.

3. Skipping validation in __init__

If the setter validates but __init__ writes self._celsius = celsius directly, Temperature(-500) creates an invalid object. In __init__, assign through the property: self.celsius = celsius.

4. Writing a getter and setter for every attribute

get_x()/set_x() pairs with no checks only make the code longer. Reach for a property when there is a real rule to enforce.

Best practices

Best practices

  • Write the object's invariants, such as "the balance is never negative", in the class docstring and check them on every change.
  • Prefix internal helpers and attributes with a single underscore; use a double underscore only when subclass name clashes are a real worry.
  • Keep property getters fast and free of side effects; use an ordinary method for heavy work such as a network call.

Mini challenge

Mini challenge: a Temperature class

Write a Temperature class with a validated celsius property and a read-only, computed fahrenheit property.

  • The celsius setter rejects values below -273.15 (absolute zero) with ValueError
  • __init__ goes through the setter too, so Temperature(-300) fails
  • fahrenheit returns celsius × 9 / 5 + 32 rounded to one decimal and has no setter
  • Change celsius to 100 and show that fahrenheit follows
temperature.py
class Temperature:
    ABSOLUTE_ZERO = -273.15

    def __init__(self, celsius):
        # TODO: assign through the property so the check runs
        pass

    # TODO: @property celsius that returns the stored value

    # TODO: @celsius.setter that raises ValueError below ABSOLUTE_ZERO

    # TODO: read-only @property fahrenheit (round to 1 decimal)


# TODO: t = Temperature(25); print celsius and fahrenheit
# TODO: set celsius to 100 and print fahrenheit again
# TODO: show that -300 and assigning to fahrenheit are both rejected

Expected: Expected output: 25 77.0 212.0 rejected: -300 is below absolute zero rejected: fahrenheit is read-only 100

Show hint

Keep the real value in self._celsius. Write only an @property for fahrenheit with no setter, and t.fahrenheit = 50 raises AttributeError.

Show solution
temperature.py
class Temperature:
    ABSOLUTE_ZERO = -273.15

    def __init__(self, celsius):
        self.celsius = celsius            # validated by the setter

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

    @celsius.setter
    def celsius(self, value):
        if value < self.ABSOLUTE_ZERO:
            raise ValueError(f"{value} is below absolute zero")
        self._celsius = value

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


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

try:
    t.celsius = -300
except ValueError as e:
    print("rejected:", e)

try:
    t.fahrenheit = 50
except AttributeError:
    print("rejected: fahrenheit is read-only")

print(t.celsius)

Quick quiz 1 / 3

Given class Box: def __init__(self): self.__size = 3 and b = Box(), which expression returns 3?

Quick quiz 2 / 3

A class has @property def balance(self): return self._balance and no setter. What does acct.balance = 10 do?

Quick quiz 3 / 3

What happens when you read p.name with @property def name(self): return self.name?

What to remember

  • Encapsulation lets data change only through checked methods or properties, protecting the object's invariants.
  • _name is an internal convention and __name triggers name mangling; neither is security.
  • @property reads a method like an attribute, and without a setter it is read-only.
  • Start with a public attribute and switch to a property when a rule appears; callers do not change.

Python Documentation — Classes — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Encapsulation (Enhanced) | Thuta Learning