Encapsulation
Encapsulation hides internal data and only exposes what's necessary. In Python, prefix an attribute with __ to make it private.
Private Attributes
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount("Alice", 1000)
acc.deposit(500)
print(acc.get_balance())
# print(acc.__balance) # AttributeError
Try it Yourself →
Property Decorators
Use @property for getters and @setter for controlled attribute access.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Too cold!")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(25)
print(t.celsius)
print(t.fahrenheit)
t.celsius = 30
print(t.fahrenheit)
Try it Yourself →