Yandex

Python Encapsulation
Keeping Things Safe Inside a Class



In the real world, we keep some things private or protected — like your phone password or your bank PIN. In Python, we can also keep some data inside a class private using a concept called encapsulation.

Encapsulation means hiding the details of how something works and only showing what's necessary. This helps keep things safe and organized.

Why Use Encapsulation?

  • To protect important data inside a class.
  • To control how the data is accessed or changed.
  • To avoid mistakes or misuse of data from outside the class.

Simple Example Without Encapsulation

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)
print(person.name)  # OK
print(person.age)   # OK

person.age = -10    # ❌ Invalid age, but Python allows it!
print(person.age)

Output

Alice
25
-10

What's the Problem?

We allowed someone to set age to -10, which doesn't make sense. We need a way to protect this value.

Encapsulation Using Private Variables

We can make variables private by using two underscores __ in front of the variable name. This tells Python: "Don’t let anyone access this directly."

class Person:
    def __init__(self, name, age):
        self.name = name
        self.__age = age  # Private variable

    def get_age(self):
        return self.__age

    def set_age(self, new_age):
        if new_age > 0:
            self.__age = new_age
        else:
            print("Age must be positive.")

person = Person("Bob", 30)
print(person.name)           # OK
print(person.get_age())      # OK

person.set_age(-5)           # Not allowed
print(person.get_age())      # Still 30

Output

Bob
30
Age must be positive.
30

Explanation

  • __age is a private variable – it cannot be accessed directly from outside.
  • get_age() is a method to read the age.
  • set_age() is a method to change the age — but only if it’s valid!

Trying to Access Private Variable Directly

print(person.__age)

Output

AttributeError: 'Person' object has no attribute '__age'

This error happens because __age is private. Python doesn’t allow direct access.

Conclusion

Encapsulation helps keep your data safe. You hide it using private variables and provide special methods to read or change the data — this gives you full control and avoids mistakes.

As you continue learning Python, encapsulation will help you write cleaner, safer, and more professional code. ✅



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M