Labs ICT
Pro Login

Encapsulation

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Encapsulation

Encapsulation hides internal data and only exposes what's necessary. In Python, prefix an attribute with __ to make it private.

Private Attributes

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

acc = BankAccount("Alice", 1000)
acc.deposit(500)
print(acc.get_balance())
# print(acc.__balance)  # AttributeError

Property Decorators

Use @property for getters and @setter for controlled attribute access.

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("Too cold!")
        self._celsius = value

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

t = Temperature(25)
print(t.celsius)
print(t.fahrenheit)
t.celsius = 30
print(t.fahrenheit)