Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Encapsulation in Python

Learn how to protect data inside a class and control how that data is accessed.

What is Encapsulation?

Encapsulation is one of the important concepts of Object-Oriented Programming.

Encapsulation means keeping data and the methods that work with that data together inside a class.

It also helps us control how the data is accessed or changed.

In simple words:

Encapsulation = Data + Methods + Controlled Access

Why Do We Need Encapsulation?

Suppose a bank account has a balance of ₹50,000. We should not allow anyone to change the balance to an invalid value directly.

Instead, we can provide methods such as deposit() and withdraw() that control how the balance changes.

Protect Data

Keep important data protected inside the class.

Control Access

Decide how data can be read or changed.

Validation

Check values before storing them.

Encapsulation Diagram

The basic idea of encapsulation can be understood with the following flow:

Class

Contains data and methods

↓
Private Data

Important information is kept inside the class.

Getter / Setter

Methods provide controlled access to the data.

User

Gets or changes data through allowed methods.

↓
Controlled Data Access

Data can be validated before it is changed.

Simple Example

Let's first understand a simple class.

class Student:

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks


student1 = Student("Rahul", 85)

print(student1.name)
print(student1.marks)

Here the student data and the related class are kept together.

This is the basic idea of keeping data and behavior inside a class.

Public Members

A public variable can normally be accessed directly from outside the class.

class Student:

    def __init__(self, name):
        self.name = name


student1 = Student("Rahul")

print(student1.name)

Output:

Rahul

name is a public attribute.

Protected Members

A protected attribute is written with a single underscore before the variable name.

class Student:

    def __init__(self, name):
        self._name = name


student1 = Student("Rahul")

print(student1._name)

The single underscore is mainly a signal to other developers that the variable is intended for internal or subclass use.

Private Members

A private attribute is written with two underscores before the variable name.

class Student:

    def __init__(self, marks):
        self.__marks = marks


student1 = Student(85)

Here __marks is intended to be private to the class.

We normally access it through methods defined inside the class.

Getter Method

A getter method is used to read the value of private data.

class Student:

    def __init__(self, marks):
        self.__marks = marks

    def get_marks(self):
        return self.__marks


student1 = Student(85)

print(student1.get_marks())

Output:

85

The get_marks() method gives us controlled access to the private variable.

Setter Method

A setter method is used to change the value of private data.

class Student:

    def __init__(self, marks):
        self.__marks = marks

    def get_marks(self):
        return self.__marks

    def set_marks(self, marks):
        self.__marks = marks


student1 = Student(70)

print(student1.get_marks())

student1.set_marks(90)

print(student1.get_marks())

Output:

70
90

Encapsulation with Validation

One major advantage of using a setter is that we can validate the value before storing it.

class Student:

    def __init__(self):
        self.__marks = 0

    def get_marks(self):
        return self.__marks

    def set_marks(self, marks):

        if 0 <= marks <= 100:
            self.__marks = marks
        else:
            print("Invalid marks")


student1 = Student()

student1.set_marks(85)

print(student1.get_marks())

student1.set_marks(150)

Output:

85
Invalid marks

Here the setter does not allow marks greater than 100 or less than 0.

Example: Bank Account 📩🌍

Let's create a bank account where balance is private.

class BankAccount:

    def __init__(self, name, balance):
        self.name = name
        self.__balance = balance

    def deposit(self, amount):

        if amount > 0:
            self.__balance += amount
            print("Amount deposited")
        else:
            print("Invalid amount")

    def get_balance(self):
        return self.__balance


account = BankAccount("Rahul", 10000)

print(account.get_balance())

account.deposit(5000)

print(account.get_balance())

Output:

10000
Amount deposited
15000

In this example, the balance is private. The user changes it through the deposit() method.

Encapsulation Step-by-Step

  1. Create a class.
  2. Create important data inside the class.
  3. Keep sensitive data private when required.
  4. Create methods to read or update the data.
  5. Add validation before changing the data.

Public vs Protected vs Private

Type Syntax Meaning
Public name Normal public attribute.
Protected _name Intended for internal or subclass use.
Private __name Intended to restrict direct access.

Benefits of Encapsulation

  • Protects important data.
  • Controls how data is changed.
  • Allows validation.
  • Keeps code organized.
  • Makes classes easier to maintain.

Common Mistakes

  • Forgetting self.
  • Using one underscore and thinking it provides complete privacy.
  • Trying to directly modify private data.
  • Not validating values before updating them.

Practice Programs

  1. Create a Student class with private marks.
  2. Create get_marks() and set_marks() methods.
  3. Allow marks only between 0 and 100.
  4. Create an Employee class with private salary.
  5. Create a BankAccount class with private balance and deposit methods.

Summary

Encapsulation means keeping data and related methods together inside a class and controlling access to that data. Python commonly uses public, protected and private naming styles. Private data can be accessed through methods such as getters and setters. Encapsulation helps protect data, validate values and keep programs organized.