Encapsulation in Python
- Read
- Discuss
Encapsulation in Python refers to hiding the internal state and implementation details of an object from the outside world and providing a public interface for interacting with the object. This allows for better control over how the object is used and ensures that the object’s internal state remains consistent.
There are two main ways to achieve encapsulation in Python:
Using private variables
Variables prefixed with a double underscore (e.g. __variable) are considered private and cannot be accessed directly from outside the class. However, they can still be accessed through getter and setter methods.
class MyClass:
def __init__(self):
self.__private_variable = "I am private"
def get_private_variable(self):
return self.__private_variable
def set_private_variable(self, value):
self.__private_variable = value
obj = MyClass()
print(obj.get_private_variable())
obj.set_private_variable("New value")
print(obj.get_private_variable())
The following will be the output.
I am private
New value
Using properties:
Properties are a more elegant way to define getter and setter methods for a variable. You can define a property on a class by using the property() built-in function, passing in the getter method as the first argument and the setter method as the second argument.
class MyClass:
def __init__(self):
self.__private_variable = "I am private"
@property
def private_variable(self):
return self.__private_variable
@private_variable.setter
def private_variable(self, value):
self.__private_variable = value
obj = MyClass()
print(obj.private_variable)
obj.private_variable = "New value"
print(obj.private_variable)
The following will be the output.
I am private
New value
It’s worth noting that in python, the convention of using double underscore before the variable name is used for name mangling which makes the variable private, but it can still be accessed by using _ClassName__variable. But it’s not recommended to access them in this way.
Encapsulation allows for better control over the object’s internal state and makes it easier to make changes to the implementation without affecting the way the object is used. It also makes it easier to ensure that the object’s internal state remains consistent and that any errors are handled in a controlled manner.
Leave a Reply
You must be logged in to post a comment.