Formation 90 min read Object-Oriented Programming

πŸ“¦ Encapsulation and Properties

Python & Data Science Chapter : Object-Oriented Programming Sub-chapter : Encapsulation and properties

Learning objectives

🎯 Objectives:\n
1Understand encapsulation\n2. Use private attributes\n3. Create properties (@property)\n4. Use setters and getters

Introduction

πŸ“– Encapsulation protects data by making it private.

Theoretical content

Encapsulation:\n
PYTHON
\nclass Account:\n    def __init__(self):\n        self._balance = 0\n    \n    @property\n    def balance(self):\n        return self._balance\n

Practical examples

πŸ’» Example: Bank account\n
PYTHON
\nclass Account:\n    def __init__(self):\n        self.__balance = 0\n

Best practices

1Use _ for protected attribute\nβœ… 2. Use __ for private attribute\nβœ… 3. Use @property for getter\nβœ… 4. Use @setter for validation

Common pitfalls

Accessing private attributes directly\n
Use properties and public methods

Summary

Encapsulation: private data\nβœ… @property: getter\nβœ… @setter: validation\nβœ… __: name mangling (strict private)

Additional resources

πŸ“š docs.python.org/3/tutorial/classes.html#private-variables