×

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

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.