Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

OOP – Encapsulation | Python Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Python Fundamentals

Lesson 28 of 55

·Python

OOP – Encapsulation

20 minutes

Course progress51%

What you'll learn

Keep these ideas in mind as you work through the lesson.

3 points
  • Prefix attributes with `__` to trigger name‑mangling (pseudo‑private).
  • Expose getters/setters via `@property` for controlled access.
  • Encapsulation protects invariants and simplifies maintenance.

OOP – Encapsulation

Encapsulation hides an object's internal state and forces interaction through a defined public interface. In Python, a leading double underscore triggers name‑mangling, making an attribute harder to access from outside.

class BankAccount:
    def __init__(self, balance=0):
        self.__balance = balance  # private attribute

    @property
    def balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

account = BankAccount(100)
account.deposit(50)
print('Balance:', account.balance)  # 150

The balance property is read‑only from the outside; only deposit can modify the underlying private attribute.

Make it stickPractice what you've learned1 quiz · 5 practical tests · Optional activities from Python FundamentalsBrowse activities
Previous lessonOOP – PolymorphismContinue to lesson 29Magic Methods and DunderBack to Python Fundamentals curriculum