Python Encapsulation

What is Encapsulation?

Encapsulation refers to the concept of bundling the data (attributes) and methods (functions) into a single unit called a class.

Encapsulation is a way to restrict direct access to some of an object’s components, providing a controlled interface to interact with the object’s internal state.

Encapsulation helps in achieving data hiding and abstraction, which are essential for creating modular and maintainable code.

Encapsulation in Python

In Python, encapsulation is achieved through the use of access modifiers. These access modifiers control the visibility of class attributes and methods from outside the class. The three common access modifiers are:

  • Public: Members are accessible from outside the class.
  • Protected: Members are accessible within the class and its subclasses.
  • Private: Members are only accessible within the class.

In the following examples, we shall see how to declare members of a class as public, protected, or private.

Examples

Let’s explore examples of encapsulation using different access modifiers in Python.

1. Public Members in Class

Public members in a class are attributes or methods that can be accessed from anywhere outside the class.

In the following program, we have a Student class with two attributes: name and age. These attributes can be accessed from outside the class. Therefore name and age attributes in this example are public members.

To define public attributes or methods in a class, name them with no prefixed underscores. Like in the following program, name and age are the public attributes of Student class, and they are named without any prefixed underscores.

Python Program

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

student = Student("Alice", 20)
print(student.name)  # Accessing public attribute
Run Code Copy

Output

Alice

In this example, the name and age attributes are accessible directly outside the class.

2. Protected Members in Class

Protected members in a class are attributes or methods that can be only be accessed from inside the same class, and from inside sub-classes.

In the following program, we have two classes: Animal and Dog. Dog class is a subclass of Animal. Inside the Animal class, we have an attribute _type, which is protected.

Please observe that, to define a protected member, we have to prefix the name of the member with an underscore symbol.

Python Program

class Animal:
    def __init__(self):
        self._type = "Unknown"

class Dog(Animal):
    def __init__(self):
        super().__init__()
        self._type = "Dog"

dog = Dog()
print(dog._type)
Run Code Copy

Output

Dog

In this example, the _type attribute is accessible within the class and its subclasses.

3. Private Member in Class

Private members in a class are attributes or methods that can be only be accessed from inside the same class.

In the following program, we have a class: BankAccount. BankAccount class has an attribute __balance, which is a private member.

Please observe that, to define a private member, we have to prefix the name of the member with two underscore symbols.

Since a private member can be accessed only inside the class, to get the balance from the BankAccount instance, we have provisioned a method get_balance() which helps us in retrieving the balance from the BankAccount.

The get_balance() method acts as an interface between the private member __balance and code outside the class.

Python Program

class BankAccount:
    def __init__(self):
        self.__balance = 0

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount()
account.deposit(100)
print(account.get_balance())  # Accessing private method
Run Code Copy

Output

100

Summary

In this tutorial of Python Classes and Objects, we have learnt about Encapsulation that promotes data hiding and abstraction. We have seen how to write public, protected, and private members in a class, and encapsulate the data in a class, with examples.

Code copied to clipboard successfully 👍