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).

class Car:
    color = 'Red' # public variable
    __gear_box_type = 'Manual' # private variable

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

class Car:
    def __init__(self):
        self.__gear_box_type = 'Manual'

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.

class Car:
    def __init__(self):
        self.__gear_box_type = 'Manual'

    # Getter
    def get_gear_box_type(self):
        return self.__gear_box_type
    
    # Setter
    def set_gear_box_type(self, gearbox):
        self.__gear_box_type = gearbox

# Instance
hyundai = Car()
print(hyundai.get_gear_box_type()) # Output: Manual

# Change Gearbox Type
hyundai.set_gear_box_type('Automatic')
print(hyundai.get_gear_box_type()) # Output: Automatic

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.

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