Lesson 18 of 30
OOP – Encapsulation and Properties
Private attributes, getters/setters, @property decorator, and data hiding.
Encapsulation
Encapsulation hides the internal state of an object and exposes only what is necessary. Python uses naming conventions rather than strict access modifiers:
_name— "protected" by convention (one underscore).__name— "private", name-mangled by Python (two underscores).
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance()) # 1500
Properties with @property
The @property decorator lets you access methods like attributes and add validation:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
import math
return math.pi * self._radius ** 2
c = Circle(5)
print(c.area) # 78.53...
c.radius = 10 # uses setter