0
0
Pythonprogramming~5 mins

Purpose of encapsulation in Python

Choose your learning style9 modes available
Introduction

Encapsulation helps keep data safe and organized inside a program. It hides details so others use it correctly without breaking it.

When you want to protect important data from being changed by mistake.
When you want to keep parts of your program separate and easy to manage.
When you want to control how data is accessed or changed.
When you want to make your code easier to understand and fix later.
Syntax
Python
class ClassName:
    def __init__(self, value):
        self.__private_variable = value  # private variable
    
    def get_variable(self):
        return self.__private_variable
    
    def set_variable(self, value):
        self.__private_variable = value

Use double underscore __ before a variable name to make it private.

Use methods (functions inside class) to get or set private data safely.

Examples
This example hides the balance and allows controlled deposit.
Python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private
    
    def get_balance(self):
        return self.__balance
    
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
Encapsulation hides the name and controls how it changes.
Python
class Person:
    def __init__(self, name):
        self.__name = name
    
    def get_name(self):
        return self.__name
    
    def set_name(self, new_name):
        self.__name = new_name
Sample Program

This program shows how encapsulation protects the speed value and only allows valid changes.

Python
class Car:
    def __init__(self, speed):
        self.__speed = speed  # private variable
    
    def get_speed(self):
        return self.__speed
    
    def set_speed(self, speed):
        if speed >= 0:
            self.__speed = speed

car = Car(50)
print(car.get_speed())  # prints 50
car.set_speed(80)
print(car.get_speed())  # prints 80
car.set_speed(-10)  # invalid, ignored
print(car.get_speed())  # still prints 80
OutputSuccess
Important Notes

Encapsulation helps avoid accidental changes to important data.

It makes your code easier to maintain and less error-prone.

Summary

Encapsulation hides data inside classes to protect it.

Use private variables and public methods to control access.

This keeps your program safe and organized.