Notes
Categories

Encapsulation in Python [ English ]

< Prev Next >

1. Introduction

Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It refers to the process of wrapping data (variables) and methods (functions) into a single unit, i.e., a class.

It also involves restricting direct access to some data, which helps in protecting the integrity of the data.

2. Definition

Encapsulation is:

The process of binding data and methods together and controlling access to data.

3. Key Features of Encapsulation

4. Data Hiding in Python

Python provides access specifiers to control access to variables:

Type Syntax Access Level
Public name Accessible everywhere
Protected _name Accessible within class and subclasses
Private __name Accessible only within the class

5. Types of Variables

5.1 Public Variable

class Student:
    def __init__(self, name):
        self.name = name   # public

s = Student("Rahul")
print(s.name)

5.2 Protected Variable

class Student:
    def __init__(self, name):
        self._name = name   # protected

5.3 Private Variable

class Student:
    def __init__(self, name):
        self.__name = name   # private

s = Student("Rahul")
# print(s.__name)  # Error

6. Accessing Private Variables

Private variables can be accessed using name mangling:

print(s._Student__name)

7. Getter and Setter Methods

Encapsulation is often implemented using getter and setter methods.

Example

class Student:
    def __init__(self):
        self.__marks = 0

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

    def get_marks(self):
        return self.__marks

s = Student()

s.set_marks(85)
print(s.get_marks())

Output

85

8. Using @property Decorator

Python provides a cleaner way using properties.

class Student:
    def __init__(self):
        self.__marks = 0

    @property
    def marks(self):
        return self.__marks

    @marks.setter
    def marks(self, value):
        self.__marks = value

s = Student()
s.marks = 90
print(s.marks)

9. Advantages of Encapsulation

10. Real-Life Example

11. Summary

< Prev Next >