×

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

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

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

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

5 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.