What is meant by encapsulation in python?Give suitable example.
What is meant by encapsulation in python?
491
28-Mar-2023
Aryan Kumar
20-Apr-2023Encapsulation is one of the fundamental concepts in object-oriented programming, which refers to the practice of hiding the implementation details of a class from the outside world and providing a public interface for interacting with it.
In Python, encapsulation is achieved through the use of access modifiers, which are special keywords that control the visibility of class attributes and methods.
There are three access modifiers in Python:
Public: The attributes and methods that are marked as public can be accessed from anywhere, both inside and outside the class.
Protected: The attributes and methods that are marked as protected can only be accessed from within the class and its subclasses.
Private: The attributes and methods that are marked as private can only be accessed from within the class. They cannot be accessed from outside the class, not even by its subclasses.
The access modifiers in Python are implemented using the following conventions:
Here is an example of encapsulation in Python:
Krishnapriya Rajeev
31-Mar-2023Python is an object-oriented language, in which the objects are functions, classes, strings and even types. These may have a type, can be passed as function arguments and may have methods and properties.
Encapsulation involves wrapping the data (variables) and the code (methods) acting on said data together as a single unit. In encapsulation, data inside one class will be hidden from other classes, and can only be accessed by methods of the same class. This is one of the key concepts of object-oriented languages like Python.
A class can be considered an example of encapsulation, as it contains variables and member functions. An example of a class in Python is given below:
We can understand encapsulation better through access modifiers in Python:
1. Protected members: These are the members of a class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. We can accomplish this by prefixing the name of the member with a single underscore.
2. Private members: These are the members of a class that cannot be accessed outside the class nor by any of its subclasses. To define a private member, we have to prefix the name of the member with a double underscore.
Example: