Encapsulation is an Object-Oriented Programming (OOP) principle that bundles data and methods together and restricts direct access to internal data.
In simple words:
Encapsulation = Data Hiding + Controlled Access
Why Encapsulation is Needed ?
- secure object data
- control how data is accessed
- improve maintainability
- reduce complexity
- follow clean design principles
Access Levels in Python
Python supports encapsulation using naming conventions:
- Public Members
- Protected Members
- Private Members
Public Members :
Public members are accessible from anywhere.
Python
class Person: def __init__(self, name): self.name = name # public p = Person("Rahul") print(p.name) Protected Members :
Protected members should be accessed only within the class or its subclasses.
They are defined using a single underscore.
Python
class Person: def __init__(self, name): self._name = name # protected class Student(Person): def show(self): print(self._name) s = Student("Anita") s.show() Private Members :
Private members are not directly accessible outside the class.
They use double underscore ( __ ), which triggers name mangling.
Python
class Person: def __init__(self, age): self.__age = age # private p = Person(25) print(p.__age) # error Getter and Setter Methods :
To safely access and modify private data, we use getter and setter methods.
Python
class Person: def __init__(self, age): self.__age = age def get_age(self): return self.__age def set_age(self, age): if age > 0: self.__age = age p = Person(22) print(p.get_age()) p.set_age(25) print(p.get_age())