Skip to main content

Python OOP

Encapsulation

Complete lesson for Encapsulation using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Encapsulation

Section: Python OOP. Python encapsulation — public attributes, protected conventions, name mangling, properties, and designing safe getters/setters.

What is encapsulation?

  • Encapsulation bundles state and behaviour, and controls how outsiders read or change that state.
  • In Python, privacy is mainly by convention and API design, not hard compiler locks like some languages.
  • Goal: protect invariants (balance never negative, email always valid) behind a clear interface.
  • Real-life: an ATM hides cash cassettes; you use a panel of well-defined operations.
class BankAccount:
    def __init__(self, holder, balance=0):
        self.holder = holder
        self._balance = balance

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

    def balance(self):
        return self._balance

acc = BankAccount("Ravi", 1000)
acc.deposit(250)
print(acc.holder, acc.balance())

Public, protected, and "private" naming

  • A leading single underscore signals "internal use".
  • A leading double underscore triggers name mangling inside the class body.
  • Trailing double underscores like __init__ are special methods — different idea.
StyleExampleMeaning
PublicnamePart of the official API
Protected (convention)_balanceInternal; subclass OK, outsiders should avoid
Private (mangled)__secretName-mangled to reduce accidental access

Why not set fields freely?

  • Direct writes can break rules: negative stock, empty usernames, invalid percentages.
  • Methods and properties give one place to validate and to adapt later.
  • You can change internal storage without breaking callers that used the public API.
class Product:
    def __init__(self, name, price):
        self.name = name
        self.set_price(price)

    def set_price(self, price):
        if price < 0:
            raise ValueError("price cannot be negative")
        self._price = price

    def get_price(self):
        return self._price

p = Product("Pen", 20)
print(p.get_price())
try:
    p.set_price(-5)
except ValueError as e:
    print(e)

@property — Pythonic getters

  • @property lets you access a method like an attribute: acc.balance instead of acc.get_balance().
  • Start with a public attribute; upgrade to a property later without changing call sites.
  • Use properties for computed values and controlled reads.
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

    @property
    def perimeter(self):
        return 2 * (self.width + self.height)

r = Rectangle(3, 4)
print(r.area, r.perimeter)

Setters with validation

  • Pair @property with @name.setter to validate on assignment.
  • Callers write obj.temperature = 36.6 while your setter enforces rules.
  • You can also define a deleter with @name.deleter when needed.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if not isinstance(value, int):
            raise TypeError("age must be int")
        if value < 0 or value > 150:
            raise ValueError("age out of range")
        self._age = value

p = Person("Asha", 20)
print(p.age)
p.age = 21
print(p.age)
try:
    p.age = -1
except ValueError as e:
    print(e)

Read-only attributes

  • Provide a getter property without a setter to make an attribute read-only from normal code.
  • Internal code can still set self._value in __init__.
  • Useful for ids, creation timestamps, and derived totals.
class Ticket:
    def __init__(self, code):
        self._code = code

    @property
    def code(self):
        return self._code

t = Ticket("T-100")
print(t.code)
try:
    t.code = "T-999"
except AttributeError as e:
    print(type(e).__name__)

Name mangling with __attr

  • Inside class Store:, __stock becomes _Store__stock at compile time for that class body.
  • This avoids accidental overrides in subclasses that also define __stock.
  • It is not true security; determined code can still access the mangled name.
class Vault:
    def __init__(self, pin):
        self.__pin = pin

    def check(self, pin):
        return pin == self.__pin

v = Vault("2468")
print(v.check("0000"))
print(v.check("2468"))
print(hasattr(v, "__pin"))
print(hasattr(v, "_Vault__pin"))

Encapsulation checklist

QuestionPrefer
Is it part of the public story?Public name, documented
Internal but subclass-visible?Single underscore _name
Easy to collide in subclasses?Double underscore __name
Needs validation on set?Property with setter
Should never change?Getter-only property
L2

Advanced — Encapsulation

Properties are descriptors

  • property is a descriptor: it hooks into attribute get/set/delete.
  • You can write custom descriptors for reusable validation across fields.
  • For most apps, @property is enough before custom descriptors.
class Celsius:
    def __init__(self, value=0):
        self.value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, v):
        if v < -273.15:
            raise ValueError("too cold")
        self._value = v

c = Celsius(10)
c.value = 20
print(c.value)

Computed properties and caching ideas

  • Properties can compute from other fields each time they are read.
  • If computation is heavy, store a cached private attribute and invalidate on change.
  • Do not hide slow I/O behind innocent-looking attribute access.
class Order:
    def __init__(self, prices):
        self.prices = list(prices)

    @property
    def total(self):
        return sum(self.prices)

    @property
    def tax(self):
        return self.total * 0.18

o = Order([100, 50, 50])
print(o.total, round(o.tax, 2))

Encapsulation vs security

  • Python encapsulation guides teammates; it does not stop a malicious local user.
  • True secrets belong in OS permissions, vaults, and server-side controls — not in __ names.
  • Still: conventions matter for readable, maintainable codebases.

Slots and attribute locking (preview)

  • __slots__ can restrict allowed attribute names and save memory.
  • That is a related control mechanism, not a full privacy system.
  • Use when you have many small objects and a fixed shape.
class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)
try:
    p.z = 3
except AttributeError as e:
    print(type(e).__name__)

Designing a clean public surface

  • Expose verbs (deposit, withdraw) for actions that change state.
  • Expose properties for simple readable facts (balance, is_active).
  • Keep helper methods private with a leading underscore.
class Counter:
    def __init__(self):
        self._n = 0

    def inc(self):
        self._n += 1

    def reset(self):
        self._n = 0

    @property
    def value(self):
        return self._n

c = Counter()
c.inc()
c.inc()
print(c.value)
c.reset()
print(c.value)
L3

Tricky Interview Points

Q1) What is encapsulation in Python?

Answer Bundling data with methods and controlling access through conventions, properties, and clear public APIs so invariants stay safe.

Q2) Are there private variables in Python?

Answer Not enforced like Java. Leading _ is a convention; leading __ triggers name mangling. Access is still possible if someone tries hard.

Q3) What is name mangling?

Answer Rewriting __attr inside a class to _ClassName__attr to avoid accidental clashes in subclasses.

Q4) What does a single leading underscore mean?

Answer Internal/protected by convention: "please treat as non-public". Tools and linters respect this signal.

Q5) Why use @property?

Answer To provide attribute-style access while running logic on get/set, including validation and computed values.

Q6) How do you make a read-only attribute?

Answer Define a @property getter without a setter; store the real value in a private/_ field set in __init__.

Q7) Is encapsulation the same as security?

Answer No. It is about API boundaries and correctness. It does not hide secrets from a determined local attacker.

Q8) Getter/setter methods vs properties?

Answer Properties are the Pythonic approach for simple field access. Explicit get_/set_ methods are less common unless they do heavy work.

Q9) Can subclasses access _value?

Answer Yes. Single-underscore names are accessible; the underscore is a warning, not a lock.

Q10) Real-life encapsulation example?

Answer A washing machine: you use start/stop/dial controls; internal motors and wiring stay hidden behind that panel.

Q11) What breaks if everything is public?

Answer Callers depend on internals; validation scatters; refactoring storage later breaks many sites.

Q12) Does __slots__ provide encapsulation?

Answer It limits attribute names and can prevent accidental attrs; it is mainly for memory/shape control, not privacy.

L4

Simple Programs

Bank account with protected balance

class BankAccount:
    def __init__(self, holder, opening=0):
        self.holder = holder
        self._balance = 0
        if opening:
            self.deposit(opening)

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

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("positive only")
        if amount > self._balance:
            raise ValueError("insufficient")
        self._balance -= amount

    @property
    def balance(self):
        return self._balance

a = BankAccount("Meena", 500)
a.deposit(100)
a.withdraw(50)
print(a.holder, a.balance)

Temperature property with setter

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 = float(value)

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

t = Temperature(0)
print(t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)

Read-only badge property

class Employee:
    _next = 100

    def __init__(self, name):
        self.name = name
        self._badge = Employee._next
        Employee._next += 1

    @property
    def badge(self):
        return self._badge

e1 = Employee("Asha")
e2 = Employee("Ravi")
print(e1.badge, e1.name)
print(e2.badge, e2.name)
try:
    e1.badge = 1
except AttributeError:
    print("badge is read-only")

Name mangling demo

class Base:
    def __init__(self):
        self.__token = "base"

    def token(self):
        return self.__token

class Child(Base):
    def __init__(self):
        super().__init__()
        self.__token = "child"

    def child_token(self):
        return self.__token

c = Child()
print(c.token())
print(c.child_token())

Product with validated discount

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("price < 0")
        self._price = value

    def discounted(self, percent):
        if percent < 0 or percent > 100:
            raise ValueError("percent out of range")
        return self._price * (1 - percent / 100)

p = Product("Notebook", 100)
print(p.discounted(10))
try:
    p.price = -1
except ValueError as e:
    print(e)

Slots preventing extra attributes

class Pair:
    __slots__ = ("left", "right")

    def __init__(self, left, right):
        self.left = left
        self.right = right

pair = Pair("a", "b")
print(pair.left, pair.right)
try:
    pair.mid = "c"
except AttributeError:
    print("extra attribute blocked")
L5

Problem Solving Tricks

  • Leading _ means "internal"; treat it as non-public in your own code.
  • Use @property when you want attribute syntax with logic underneath.
  • Validate in setters so bad values never enter the object.
  • Getter-only properties make nice read-only ids and derived values.
  • Name mangling is for avoiding clashes, not hiding treasures.
  • Prefer verbs for state-changing operations (deposit) over exposing raw fields.
  • You can start with public attrs and later swap in properties without breaking callers.
  • Do not put passwords in mangled attributes and call it security.
  • __slots__ helps shape/memory; still document the public API separately.
  • Keep invariants in one place — constructors and setters — not scattered across callers.
L6

Practice Programs List

  1. Wrap a bank balance in _balance and expose it with a read-only property.
  2. Add a temperature setter that rejects values below absolute zero.
  3. Build Employee with a read-only auto-increment badge property.
  4. Demonstrate name mangling with a Base/Child pair each defining __token.
  5. Convert get_price/set_price methods into a price property.
  6. Create a computed area property on Rectangle.
  7. Use __slots__ on a tiny class and show that extra attrs fail.
  8. Refactor a class that exposes a public list attribute into a controlled add_item API.
  9. Write a product discount method that validates percent range.
  10. List five ATM-like real-life encapsulation examples and model one.
  11. Show that obj._balance = -1 is possible and explain why API methods are still better.
  12. Design a class where all mutation goes through methods; attributes are read-only properties.