Member-only story
Encapsulation in Python: Object-Oriented Programming
Introduction
Encapsulation is a core concept of OOP (Object Oriented Programming) that every developer should seek to understand. This article will explain what encapsulation is, what its benefits are, and how to write encapsulated code in Python!
What is Encapsulation?
Encapsulation means containing all important information inside an object, and only exposing selected information to the outside world. In terms of OOP, this means keeping all fields private, and providing public methods for accessing and setting this data if it is needed outside the class.
This is done to protect the data from accidental modification, and to provide a clear interface for interacting with the object.
Encapsulation in Python
Here’s an example of a class for a Car
implemented using encapsulation in Python:
class Car:
def __init__(self, make, model):
self._make = make
self._model = model
def set_make(self, make):
self._make = make
def set_model(self, model):
self._model = model
def get_make(self):
return self._make
def get_model(self):
return self._model