Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 07

Encapsulation and Abstraction — Hide a Field, Show a Method

Hide a Python instance field with a double underscore, then let callers use a method so they see the result without the stored detail.

Intermediate25 min
Encapsulation and abstraction hero Module 17 Lesson 7 hidden field

Encapsulation keeps a detail inside the object. Abstraction is what the caller gets instead: the essential result, without handling the hidden field.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • What encapsulation and abstraction mean
  • How a double underscore hides an instance field
  • Why the public method is the abstraction
  • What name mangling actually does

The picture

Callers use the method, not the stored code

Encapsulation is hiding selected data or methods from the code outside the class. In Python you prefix an instance name with __.

text
self.__code = m
def __lock(self):
    ...

Use this on instance fields and instance methods when the outside code should not touch them directly. Class data, class methods, and static methods are normally left public because they are shared utilities.

A constructor itself is not given a private name. The fields it stores can be private.

Abstraction is using the essential part and ignoring the hidden part. The essential part here is reveal(). The caller does not set __code and does not read it.

Python implements the double underscore by name mangling. self.__code inside Locker is stored as _Locker__code. locker.__code raises AttributeError, but the mangled name still exists. This is a naming barrier for accidental access, not encryption. Do not treat it as a security boundary for real secrets.

The lesson example hides a door code and exposes only a short check.

Example

python
class Locker:
    def __init__(self, m):
        self.__code = m

    def reveal(self):
        return "code ends with " + self.__code[-2:]

locker = Locker("4812")
print(locker.reveal())

The caller prints a short confirmation. The full code stays on the instance under the mangled name. In the playground, the direct locker.__code read fails, and the method still works. That pair is encapsulation plus abstraction.

Key takeaways

  • Encapsulation hides instance details with __

  • Abstraction is the public method the caller actually uses

  • __code becomes _Locker__code inside that class

  • This is name mangling, not encryption

  • Next: Inheritance — a child class reuses a parent class

  • Previous: Destructors

Loading playground…

Check your understanding

Encapsulation and abstraction quiz

Encapsulation means:

1 / 10