Encapsulation in Python (original) (raw)

Last Updated : 27 Feb, 2025

In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage.

Table of Content

Encapsulation is the process of hiding the internal state of an object and requiring all interactions to be performed through an object’s methods. This approach:

Python achieves encapsulation through **public, **protected and **private attributes.

Encapsulation in Python

Encapsulation Python

How Encapsulation Works :

Example of Encapsulation

Encapsulation in Python is like having a bank account system where your account balance (data) is kept private. You can’t directly change your balance by accessing the account database. Instead, the bank provides you with methods (functions) like deposit and withdraw to modify your balance safely.

Public Members

Public members are accessible from anywhere, both inside and outside the class. These are the default members in Python.

**Example:

Python `

class Public: def init(self): self.name = "John" # Public attribute

def display_name(self):
    print(self.name)  # Public method

obj = Public() obj.display_name() # Accessible print(obj.name) # Accessible

`

**Explanation:

**Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.

Protected members

Protected members are identified with a single underscore ****(_)**. They are meant to be accessed only within the class or its subclasses.

**Example:

Python `

class Protected: def init(self): self._age = 30 # Protected attribute

class Subclass(Protected): def display_age(self): print(self._age) # Accessible in subclass

obj = Subclass() obj.display_age()

`

**Explanation:

Private members

Private members are identified with a double underscore ****(__)** and cannot be accessed directly from outside the class. Python uses name mangling to make private members inaccessible by renaming them internally.

**Note: Python’s private and protected members can be accessed outside the class through python name mangling.

Python `

class Private: def init(self): self.__salary = 50000 # Private attribute

def salary(self):
    return self.__salary  # Access through public method

obj = Private() print(obj.salary()) # Works #print(obj.__salary) # Raises AttributeError

`

**Explanation: