0Pricing
Learn AI with Python · Lesson

Encapsulation and Abstraction

Understand how to hide complexity and expose only what's necessary.

1

Introduction to Encapsulation and Abstraction

Encapsulation and abstraction are fundamental principles of Object-Oriented Programming (OOP) that help manage complexity and improve code organization.

Encapsulation restricts direct access to an object's data, while abstraction hides implementation details and exposes only essential features.

Encapsulation and Abstraction — illustration 1

2

What Is Encapsulation?

Encapsulation means bundling data (attributes) and methods together within a class and restricting direct access to them.

# Example of encapsulation
class Person:
    # Private attribute (indicated by double underscores)
    def __init__(self, name):
        self.__name = name

    # Public method to access the private attribute
    def get_name(self):
        return self.__name

person = Person("Alice")
# Accessing private data via a public method
print(person.get_name())

All lessons in this course

  1. Classes and Objects
  2. Attributes and Methods
  3. Inheritance
  4. Polymorphism
  5. Encapsulation and Abstraction
  6. Magic Methods (__str__, __repr__, etc.)
← Back to Learn AI with Python