Unveiling Encapsulation in Python: An Expedition into OOP's Protective Shield
Introduction and Actualization
Are you ready for an exciting Python journey? Today's destination is Encapsulation, a pillar of OOP. Encapsulation bundles related data and methods — much like yolk and egg white are nestled inside an eggshell—within the framework of a class. This lesson will help us understand encapsulation's roles, cover public and private variables, explain getters and setters, and reveal how encapsulation hides implementation details.
Encapsulation: A Brief Meet and Greet
Encapsulation harmonizes related variables and functions, protecting them from unauthorized external access. Take a car, for instance — it's an elaborate piece of machinery (data) controlled by various user-friendly gadgets (methods). In Python, an object bundles class variables and functions, thus providing efficient data manipulation and masking complexity.
Python and Public/Private Variables
Classes hosted in Python have variables and methods. Variables, such as the color or model of a car class, can either be public (accessible everywhere) or private (hidden).
__gear_box_type is a private variable, you can mention it by the two underscores (__) at the beginning of its name. To access or modify it, we use getters and setters, which we will discuss in the next section of this lesson.
Getters and Setters: Python's Protectors
Getters retrieve attribute values, while setters assign values to them. They protect data from unauthorized changes.
Observe a simple class, Car, which has a private variable, __gear_box_type:
Since __gear_box_type is a private variable, you cannot access it like you would a public variable. You need to use a getter or setter method.
Here, we use get_gear_box_type and set_gear_box_type to access the private variable inside the Car class. This is what encapsulation is all about - protecting and limiting access and hiding implementation from the caller.
