Formation
90 min read
Object-Oriented Programming
π¦ 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\nPractical examples
π» Example: Bank account\n
PYTHON
\nclass Account:\n def __init__(self):\n self.__balance = 0\nBest 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