Home Tutorials Python OOP Concepts Encapsulation
Encapsulation

Encapsulation


8. Encapsulation

Encapsulation means bundling data and methods together in a class and controlling how that data is accessed. Python commonly shows encapsulation using public, protected-like, and private name conventions.

Syntax

class ClassName:
    def __init__(self):
        self.public_var = 1
        self._protected_var = 2
        self.__private_var = 3

Example

class Bank:
    def __init__(self, balance):
        self.__balance = balance
        
    def deposit(self, amount):
        self.__balance += amount
        
    def show_balance(self):
        print("Balance =", self.__balance)

b = Bank(1000)
b.deposit(500)
b.show_balance()

Output

Balance = 1500
Example

🏋️ Test Yourself With Exercises

Take our quiz on Encapsulation to test your knowledge.

Browse Quizzes »