🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Encapsulation

AI & DATA SCIENCE // encapsulation

Encapsulation means bundling an object's data with the methods that operate on it, and controlling how that data is accessed from outside the class.

Syntax

class Account:
    def __init__(self):
        self._balance = 0     # convention: internal
        self.__secret = None  # name-mangled: strongly internal

Deep Dive Course

Python doesn't have true private attributes enforced by the language the way some other languages do — instead, it relies on naming conventions: a single leading underscore signals 'internal, please don't touch this from outside the class' as a courtesy to other developers, while a double leading underscore triggers name mangling, rewriting the attribute internally to include the class name, which makes accidental external access or accidental clashes in subclasses much less likely, though still not truly impossible. Encapsulation is typically paired with methods, or the @property decorator, that provide controlled, validated access to internal state instead of letting external code read or write it directly.

1Understanding Encapsulation

Python doesn't have true private attributes enforced by the language the way some other languages do — instead, it relies on naming conventions: a single leading underscore signals 'internal, please don't touch this from outside the class' as a courtesy to other developers, while a double leading underscore triggers name mangling, rewriting the attribute internally to include the class name, which makes accidental external access or accidental clashes in subclasses much less likely, though still not truly impossible. Encapsulation is typically paired with methods, or the @property decorator, that provide controlled, validated access to internal state instead of letting external code read or write it directly.

💡

Python's philosophy is often summarized as 'we're all consenting adults here' — a single underscore is a strong hint, not a hard barrier, so encapsulation in Python relies on convention and trust rather than a compiler-enforced access modifier.

editor.html
class BankAccount:
    def __init__(self, balance):
        self._balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

account = BankAccount(100)
account.deposit(50)
print(account._balance)
localhost:3000

2Practical Example

Here is a real-world application of Encapsulation showing how it is used in production Python code.

editor.html
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

t = Temperature(20)
print(t.fahrenheit)
localhost:3000

3Best Practices

Follow these guidelines when working with Encapsulation:

1. Use a single leading underscore to mark attributes/methods as internal implementation details not meant for external use

2. Use @property to expose a controlled, validated 'view' of internal state instead of letting external code set an attribute directly to any value

3. Reserve double leading underscores, name mangling, for cases where accidental overriding or access from a subclass would specifically cause bugs, not as the default privacy convention

⚠️

Tip: Python's philosophy is often summarized as 'we're all consenting adults here' — a single underscore is a strong hint, not a hard barrier, so encapsulation in Python relies on convention and trust rather than a compiler-enforced access modifier.

editor.html
class BankAccount:
    def __init__(self, balance):
        self._balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

account = BankAccount(100)
account.deposit(50)
print(account._balance)
localhost:3000

Examples

Example 01Basic Usage
class BankAccount:
    def __init__(self, balance):
        self._balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

account = BankAccount(100)
account.deposit(50)
print(account._balance)
Example 02Advanced Example
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

t = Temperature(20)
print(t.fahrenheit)

Best Practices

  • Use a single leading underscore to mark attributes/methods as internal implementation details not meant for external use
  • Use @property to expose a controlled, validated 'view' of internal state instead of letting external code set an attribute directly to any value
  • Reserve double leading underscores, name mangling, for cases where accidental overriding or access from a subclass would specifically cause bugs, not as the default privacy convention

Interview Question

Since Python has no truly private attributes, what actually stops external code from accessing an attribute named with a single leading underscore?

Hint: Think about convention versus enforcement.

Nothing at the language level — a single leading underscore is purely a naming convention communicating 'this is an internal implementation detail', and Python does not prevent external code from reading or writing it. Double leading underscores go a step further with name mangling, rewriting the attribute to include the class name, which discourages accidental access and accidental clashes in subclasses, but it's still possible to access it if you know the mangled name. Python favors trusting developers over compiler-enforced access control.

Exercises

MediumPractice using Encapsulation in a real scenario.
View Solution
class BankAccount:
    def __init__(self, balance):
        self._balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

account = BankAccount(100)
account.deposit(50)
print(account._balance)

Frequently Asked Questions

Since Python has no truly private attributes, what actually stops external code from accessing an attribute named with a single leading underscore?

Nothing at the language level — a single leading underscore is purely a naming convention communicating 'this is an internal implementation detail', and Python does not prevent external code from reading or writing it. Double leading underscores go a step further with name mangling, rewriting the attribute to include the class name, which discourages accidental access and accidental clashes in subclasses, but it's still possible to access it if you know the mangled name. Python favors trusting developers over compiler-enforced access control.

Related Functions

class-keywordclass-methods-classmethoddunder-methods