Object-oriented programming (OOP) is a programming paradigm that offers a means of structuring a software program around objects and data, rather than functions and logic. An object is a thing or concept that can be clearly defined. In OOP, each object is an instance of a class. Python is a programming language that supports object-oriented programming and one of the main features of OOP is encapsulation.
6.4. Object-Oriented Programming in Python: Encapsulation in Python
Encapsulation is one of the main characteristics of object-oriented programming. It refers to the practice of hiding the internal details of how an object works and exposing only the interfaces through which that object can be used. In other words, encapsulation is a way of hiding the implementation details of an object and exposing only the methods and properties necessary to interact with that object.
In Python, encapsulation is performed using private and protected methods and variables. A private variable is a variable that cannot be accessed or modified directly outside the class where it is defined. A protected variable is similar to a private variable, but can be accessed and modified in subclasses.
To declare a variable as private in Python, we prefix the variable name with two underscores (__). For example, __variable_name. To declare a variable as protected, we prefix the variable name with an underscore (_). For example, _variable_name.
Encapsulation in Python is not as strict as in other object-oriented programming languages, such as Java or C++. In Python, it's more of a convention than a hard-and-fast rule. However, it is good practice to follow this convention to make the code easier to understand and maintain.
Let's consider the following example of encapsulation in Python:
class ExampleEncapsulation: def __init__(self): self.__private_variable = "I am a private variable" self._variable_protected = "I am a protected variable" def get_private_variable(self): return self.__private_variable def get_protected_variable(self): return self._protected_variable
In this example, we create a class called EncapsulationExample. Within this class, we define two variables: a private variable (__private_variable) and a protected variable (_protected_variable). We also define two methods to obtain the values of these variables.
If we try to access the private variable directly outside the class, we will get an error. However, we can access the value of the private variable using the get_private_variable() method. Likewise, although we can access the protected variable directly outside the class, it is good practice to access it using the get_protected_variable() method.
Encapsulation in Python helps us make our code more secure and easier to maintain. It allows us to hide the implementation details of an object and expose only the interfaces necessary to interact with that object. This makes the code easier to understand and less prone to errors.