×

Python Encapsulation

What is meant by Encapsulation?

The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation.

The motive of Encapsulation: Preventing accidental modifications of data.

 Comparing data encapsulation with real-time examples:

Consider a Mobile phone. We use all the features that are involved or embedded within the phone. We access all these features for different purposes and different implementations. But the access is restricted for changing or modifying most features.

In the same way, we use much software which functions with many software tools, but any of those features or software tools cannot be accessed or modified. The access is restricted for a purpose. If there is any scope to access these internal features of the software, we might make some modifications or changes accidentally. These modifications might lead to the destruction of the software, followed by the destruction of the device.

To prevent all such types of issues, the encapsulation concept is implemented. Encapsulation allows you to get more control over the code by capsulizing or combining the code so that small implementations can be done without affecting the remaining code. It protects the data using private variables and private methods. Along with giving protection, it wraps the complete data into a single unit.

In order to implement Encapsulation within the code, we generally use Private Attributes. Let us have a look at those attributes and understand in what way they are used.

Private Attributes:

The attributes that can be either accessed or modified only by using that particular object’s method and can be accessed neither from outside the class nor within the derived class are known as Private Attributes.

Generally, Private Attributes start with " single underscore ", i.e., " _ ". To represent that the given attribute is private, its name should be started with a single underscore or “_”.

Syntax:

self._attributename = “ Hello “

Example program where Private Attributes are used for implementing Encapsulation:

  class A:
   def __init__ (self):
		  self.a=20
		  self._b=40
   class B(A)
	  def __init__ (self):
		A.__init__(self):
		     print(“The value of private attribute present in the Base class A is”)
		     print(self._c) 
   obj1 = A()
   print(obj1.b)

Output:

AttributeError: ‘A’ object has no attribute ‘b’

Explanation:

Let class A be the Base class and class B be the Derived class. As we know, the private attribute " _b " is declared in the Base class, i.e., class A. Class B is the derived class of A. So, all methods, variables and attributes ( excluding private ) present in the Base class A can be accessed by the objects declared in Derived class B. An object " obj1 " is created in the Base class A. The print statement is passed to print the value of attribute "b". As attribute b is private, it is unable to recognize general attribute b but searching for the existing private attribute “ _b “. That’s the reason for getting an Attribute error in the output.

Let us modify the line that caused an error and try the same example again.

class A:
   def __init__ (self):
		  self.a=20
		  self._b=40
   class B(A)
	  def __init__ (self):
		A.__init__(self):
		     print(“The value of private attribute present in the Base class A is”)
		     print(self._c) 
   obj1 = B()
   print(obj1._b)

Output:

   The value of the private attribute present in the Base class is 40
   40
   40

Explanation:

Let class A be the Base class and class B be the Derived class. The private attribute " _b " is declared in the Base class, i.e., class A. Class B is the derived class of A. So, all methods, variables and attributes ( excluding private ) present in the Base class A can be accessed by the objects declared in Derived class B. Let’s change the object creation from A to B. An object “ obj1 “ is created in the Derived class B. The print statement is passed to print the value of the private attribute or member “_b". As attribute b is private, we had mentioned an underscore before the name and stated the attribute to print. Now, we got a successful output without any error representing the passage of the private attribute. We get the same output in the case of private variables and private methods.  


Related Topics

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.