PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Encapsulation in Python

Encapsulation in Python

Updated on: December 4, 2026 | 30 Comments

Encapsulation is one of the four fundamental concepts of object-oriented programming (OOP), along with abstraction, inheritance, and polymorphism. This lesson covers what encapsulation is and how to implement it in Python.

After reading this article, you will learn:

  • Encapsulation in Python
  • The need for encapsulation
  • Data hiding using public, protected, and private members
  • How name mangling works
  • Data hiding vs. encapsulation
  • Getter and setter methods, and the Pythonic @property decorator
  • Benefits of encapsulation

Table of contents

  • What is Encapsulation in Python?
  • Access Modifiers in Python
  • Public Member
  • Private Member
    • Public method to access private members
    • Name Mangling to access private members
  • Protected Member
  • Getters and Setters in Python
    • The Pythonic Way: @property
  • Data Hiding vs. Encapsulation
  • Advantages of Encapsulation

What is Encapsulation in Python?

Encapsulation in Python describes the concept of bundling data and methods into a single unit. When you create a class, you are implementing encapsulation. A class is an example of encapsulation because it binds all the data members (instance variables) and the methods that work on them into a single unit.

Implement encapsulation using a class
Implement encapsulation using a class

Example:

In this example, we create an Employee class that stores employee attributes such as name and salary as instance variables and implements behavior using the work() and show() instance methods.

class Employee:
    # constructor
    def __init__(self, name, salary, project):
        # data members
        self.name = name
        self.salary = salary
        self.project = project

    # method
    # to display employee's details
    def show(self):
        # accessing public data member
        print("Name:", self.name, 'Salary:', self.salary)

    # method
    def work(self):
        print(self.name, 'is working on', self.project)

# creating object of a class
emp = Employee('Jessa', 8000, 'NLP')

# calling public method of the class
emp.show()
emp.work()Code language: Python (python)

Output:

Name: Jessa Salary: 8000
Jessa is working on NLP

Using encapsulation, we can hide an object’s internal representation from the outside. This is called information hiding.

Encapsulation also lets us restrict direct access to variables and methods, and prevent accidental data modification, by making some data members and methods private within a class.

When a class deals with sensitive data, giving outside code access to every variable is not a good choice. Encapsulation lets us restrict access to methods and variables from outside the class.

For example, suppose an attribute is hidden from the outside of an object, and you provide methods that give read or write access to it. Then you control how the object’s internal state is read and changed. Encapsulation lets other code use the data it needs without giving it full access to every variable of the class. This protects an object’s data from other objects.

Access Modifiers in Python

Encapsulation can be achieved by declaring the data members and methods of a class as private or protected. Unlike Java or C++, Python has no public, private, or protected keywords. Instead, it uses naming conventions: a single underscore or double underscores at the start of a name.

Access modifiers limit access to the variables and methods of a class. Python has three levels:

  • Public member (name): Accessible anywhere, from inside or outside the class.
  • Private member (__name): Accessible only within the class.
  • Protected member (_name): Meant to be used only within the class and its subclasses.
Data hiding using access access modifiers
Data hiding using access modifiers

Public Member

Public data members are accessible inside and outside of a class. All members of a class are public by default.

Example:

class Employee:
    # constructor
    def __init__(self, name, salary):
        # public data members
        self.name = name
        self.salary = salary

    # public instance methods
    def show(self):
        # accessing public data member
        print("Name:", self.name, 'Salary:', self.salary)

# creating object of a class
emp = Employee('Jessa', 10000)

# accessing public data members
print("Name:", emp.name, 'Salary:', emp.salary)

# calling public method of the class
emp.show()Code language: Python (python)

Output

Name: Jessa Salary: 10000
Name: Jessa Salary: 10000

Private Member

We can protect variables in a class by marking them private. To define a private variable, add two underscores as a prefix at the start of the variable name, for example __salary.

Private members are meant to be accessed only within the class. We can’t access them directly from an object using their original name.

Example:

class Employee:
    # constructor
    def __init__(self, name, salary):
        # public data member
        self.name = name
        # private member
        self.__salary = salary

# creating object of a class
emp = Employee('Jessa', 10000)

# accessing private data members
print('Salary:', emp.__salary)Code language: Python (python)

Output

AttributeError: 'Employee' object has no attribute '__salary'

In the above example, __salary is a private variable, so we can’t access it from outside the class using that name.

We can access private members from outside a class in two ways:

  • Create a public method that accesses the private members
  • Use name mangling

Let’s see each one.

Public method to access private members

Example: Access a private member from outside the class using an instance method

class Employee:
    # constructor
    def __init__(self, name, salary):
        # public data member
        self.name = name
        # private member
        self.__salary = salary

    # public instance methods
    def show(self):
        # private members are accessible from a class
        print("Name:", self.name, 'Salary:', self.__salary)

# creating object of a class
emp = Employee('Jessa', 10000)

# calling public method of the class
emp.show()Code language: Python (python)

Output:

Name: Jessa Salary: 10000

Name Mangling to access private members

Python doesn’t truly hide private members. Instead, it uses name mangling: any member name inside a class that starts with two underscores (and doesn’t end with two underscores) is automatically renamed to _ClassName__member. For example, __salary in the Employee class is stored as _Employee__salary.

That’s why emp.__salary fails, but emp._Employee__salary works. Name mangling applies only to private (double underscore) members, not to protected (single underscore) members.

Example: Access private member

class Employee:
    # constructor
    def __init__(self, name, salary):
        # public data member
        self.name = name
        # private member
        self.__salary = salary

# creating object of a class
emp = Employee('Jessa', 10000)

# see how Python actually stored the private member
print(emp.__dict__)

# direct access to private member using name mangling
print('Salary:', emp._Employee__salary)Code language: Python (python)

Output

{'name': 'Jessa', '_Employee__salary': 10000}
Salary: 10000

Note: The main purpose of name mangling is to avoid accidental name clashes in subclasses, not to provide security. If a parent class and a child class both use self.__secret, they are stored as two different attributes, _Parent__secret and _Child__secret, so the child doesn’t overwrite the parent’s value. Accessing _ClassName__member from outside works, but you should avoid it in real code.

Protected Member

Protected members are meant to be accessed within the class and its subclasses. To define a protected member, prefix the member name with a single underscore _.

Use protected data members with inheritance, when you want child classes to use a member but don’t want it to be part of the class’s public interface.

Important: Python doesn’t enforce protected access. A single underscore is only a convention that tells other programmers “this is internal, don’t use it from outside.” As the last line of the following example shows, the member is still accessible from outside the class.

Example: Protected member in inheritance.

# base class
class Company:
    def __init__(self):
        # Protected member
        self._project = "NLP"

# child class
class Employee(Company):
    def __init__(self, name):
        self.name = name
        super().__init__()

    def show(self):
        print("Employee name :", self.name)
        # Accessing protected member in child class
        print("Working on project :", self._project)

c = Employee("Jessa")
c.show()

# Direct access protected data member (works, but not recommended)
print('Project:', c._project)Code language: Python (python)

Output

Employee name : Jessa
Working on project : NLP
Project: NLP

Getters and Setters in Python

To control how data is read and changed, we use getter and setter methods. A getter method reads a data member, and a setter method modifies it. Together they ensure data encapsulation.

In Python, private variables aren’t truly hidden, as they are in some other languages. Getters and setters are typically used:

  • To avoid direct access to private variables
  • To add validation logic before setting a value

Example

class Student:
    def __init__(self, name, age):
        # public member
        self.name = name
        # private member
        self.__age = age

    # getter method
    def get_age(self):
        return self.__age

    # setter method
    def set_age(self, age):
        self.__age = age

stud = Student('Jessa', 14)

# retrieving age using getter
print('Name:', stud.name, stud.get_age())

# changing age using setter
stud.set_age(16)

# retrieving age using getter
print('Name:', stud.name, stud.get_age())Code language: Python (python)

Output

Name: Jessa 14
Name: Jessa 16

Let’s take another example that uses encapsulation to hide information and validate a value before changing an object’s attribute (data member).

Example: Information hiding and conditional logic for setting an object’s attributes

class Student:
    def __init__(self, name, roll_no, age):
        # public member
        self.name = name
        # private members to restrict access
        # avoid direct data modification
        self.__roll_no = roll_no
        self.__age = age

    def show(self):
        print('Student Details:', self.name, self.__roll_no)

    # getter methods
    def get_roll_no(self):
        return self.__roll_no

    # setter method to modify data member
    # condition to allow data modification with rules
    def set_roll_no(self, number):
        if number > 50:
            print('Invalid roll no. Please set correct roll number')
        else:
            self.__roll_no = number

jessa = Student('Jessa', 10, 15)

# before Modify
jessa.show()
# changing roll number using setter
jessa.set_roll_no(120)


jessa.set_roll_no(25)
jessa.show()Code language: Python (python)

Output:

Student Details: Jessa 10
Invalid roll no. Please set correct roll number
Student Details: Jessa 25

The Pythonic Way: @property

Writing get_age() and set_age() works, but in Python the preferred way is the built-in @property decorator. It turns methods into a getter and a setter that are used like a normal attribute (stud.age), while still running your validation code behind the scenes.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age   # calls the setter below

    @property
    def age(self):
        # getter
        return self.__age

    @age.setter
    def age(self, value):
        # setter with validation
        if value < 0 or value > 120:
            raise ValueError('Age must be between 0 and 120')
        self.__age = value

stud = Student('Jessa', 14)
print('Name:', stud.name, 'Age:', stud.age)

# looks like normal attribute access, but runs the setter
stud.age = 16
print('Name:', stud.name, 'Age:', stud.age)

try:
    stud.age = -5
except ValueError as e:
    print('Error:', e)Code language: Python (python)

Output:

Name: Jessa Age: 14
Name: Jessa Age: 16
Error: Age must be between 0 and 120

Because the validation also runs in __init__() (through self.age = age), an invalid age can’t get into the object at all. If you define only the @property getter and no setter, the attribute becomes read-only.

Data Hiding vs. Encapsulation

These two terms are related but not the same:

  • Encapsulation is about bundling: putting data and the methods that work on that data together in one unit (a class).
  • Data hiding is about restricting access: preventing outside code from directly reading or changing an object’s internal data, using private or protected members.

Data hiding is one way to achieve encapsulation. A class with only public members is still encapsulated, because it bundles data and methods, but it doesn’t hide its data.

Advantages of Encapsulation

  • Data protection: Encapsulation helps protect an object’s data from accidental or invalid changes. Private and protected members, together with setters that validate input, keep the object in a valid state.
  • Data hiding: Users of a class don’t need to know what happens behind the scenes. They just call a setter (or assign to a property) to change data, and a getter to read it. How those methods work internally is hidden from them.
  • Simplicity and maintainability: You can change a class’s internal implementation without breaking code that uses it, as long as the public interface stays the same. This keeps classes loosely coupled.
  • Readability: Bundling data and methods within a class makes code more organized, readable, and maintainable.

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com