×

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

Unicode to String in Python

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 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.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Python sklearn train_test_split

Sklearn: One of the most beneficial open-source libraries for learning algorithms in Python is, without a doubt, Sklearn or Scikit-Learn. The most effective tools for statistical modeling and machine learning are all included in...

6 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.