Interview Questions, Answers and Tutorials

Encapsulation

Encapsulation

What is Encapsulation?

Imagine you have a treasure chest. You don’t want just anyone to open it and take the treasures inside, right? So, you put a lock on it. The lock is like a shield, protecting the treasures from being accessed by just anyone.

In programming, encapsulation is like putting a lock on your data. It’s a way to protect your data from being accessed or modified by code that shouldn’t be messing with it.

How does Encapsulation Work?

Encapsulation in Python is often achieved using classes and objects.

Classes are like blueprints. They define what an object will be able to do and what data it will contain.

Objects are instances of these blueprints. They are like the actual things built from the blueprint.

So, when we talk about encapsulation, we’re talking about hiding data within objects and only allowing access to it through special methods. These methods act as the locks on our treasure chest.

Example with Python Code:

Let’s create a Car class. Our car has some properties like color and speed. We want to protect these properties from being directly accessed and modified from outside the class.

class Car:
    def __init__(self, color, speed):
        self._color = color  # _color is a protected attribute
        self._speed = speed  # _speed is a protected attribute
    
    def get_color(self):
        return self._color
    
    def get_speed(self):
        return self._speed
    
    def set_color(self, color):
        self._color = color
    
    def set_speed(self, speed):
        self._speed = speed

In this code:

  • We define a class Car with two properties: _color and _speed.
  • We use methods like get_color() and set_color() to access and modify the _color property.

Practice Questions:
  1. What is encapsulation in Python?
    • A) Protecting data from being accessed or modified by unauthorized code.
    • B) Creating objects from classes.
    • C) Defining blueprints for objects.

  1. What is the purpose of using methods like get_color() and set_color()?
    • A) To access and modify the _color property.
    • B) To create new instances of the Car class.
    • C) To define the color of the car.

Solutions:
  1. Answer: A) Protecting data from being accessed or modified by unauthorized code.
  2. Answer: A) To access and modify the _color property.

Encapsulation helps keep our code organized, secure, and easier to manage. By hiding the implementation details, it allows us to change how things work internally without affecting the code that uses it. Just like a treasure chest, our data stays safe and secure!