PythonEncapsulation

Encapsulation in Python

with clear explanations and 5+ example programs — same format and style:


Encapsulation in Python

Encapsulation is a key principle of Object-Oriented Programming (OOP) that focuses on:

Hiding internal data of an object Controlling how data is accessed or modified Providing a public interface while protecting internal state

In simple terms — Encapsulation helps in protecting object integrity by preventing outside code from directly accessing or changing internal attributes.


Why Use Encapsulation?

BenefitDescription
Protect internal stateAvoid accidental changes to object data
Control how data is accessedAllow only specific ways to view or modify data
Improve code maintainabilityReduce bugs by enforcing rules for object state

Levels of Access in Python

TypePrefixExample
PublicNo _self.name
Protected_varself._salary
Private__varself.__age

Note: In Python, encapsulation is by convention, not strict enforcement — but widely followed.


Example 1: Public Attribute

example1_public.py
class Person:
    def __init__(self, name):
        self.name = name
 
p = Person("Alice")
print(p.name)
output.txt
Alice

Example 2: Protected Attribute

example2_protected.py
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self._salary = salary  # protected
 
e = Employee("John", 50000)
print(e.name)
print(e._salary)  # discouraged: direct access to protected attribute
output.txt
John
50000

Explanation: By convention, attributes starting with _ are considered protected — internal use only.


Example 3: Private Attribute

example3_private.py
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private
 
    def show_balance(self):
        print(f"Balance: ₹{self.__balance}")
 
account = BankAccount(10000)
account.show_balance()
 
# print(account.__balance)  # This will cause an error
output.txt
Balance: ₹10000

Example 4: Access Private Attribute via Method

example4_getter.py
class Car:
    def __init__(self, model, price):
        self.model = model
        self.__price = price
 
    def get_price(self):
        return self.__price
 
c = Car("Tesla", 5000000)
print(c.model)
print("Price:", c.get_price())
output.txt
Tesla
Price: 5000000

Example 5: Using Setters and Getters

example5_getter_setter.py
class Student:
    def __init__(self, name):
        self.__name = name
 
    def get_name(self):
        return self.__name
 
    def set_name(self, new_name):
        if isinstance(new_name, str) and new_name.strip() != "":
            self.__name = new_name
        else:
            print("Invalid name.")
 
s = Student("Tom")
print(s.get_name())
 
s.set_name("Jerry")
print(s.get_name())
output.txt
Tom
Jerry

Example 6: Name Mangling

example6_name_mangling.py
class Demo:
    def __init__(self):
        self.__hidden = "secret"
 
d = Demo()
# Access private attribute with name mangling (not recommended)
print(d._Demo__hidden)
output.txt
secret

Explanation: Private attributes are internally renamed using _ClassName prefix — called name mangling.


Key Points

Use _var to indicate protected attributes. Use __var to indicate private attributes. Always access private data via getters and setters. Encapsulation improves security, readability, and maintainability.


Summary

  • Encapsulation is about hiding internal object data.
  • Control object data with public, protected, and private attributes.
  • Use getter and setter methods to manage access.
  • Helps protect object integrity and prevent bugs.

Next, we will explore Polymorphism — how different classes can share behavior while maintaining their own identity.