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, :

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal