Private Attributes, @property & Setters Explained - Python OOP Encapsulation Tutorial #21
Video: Private Attributes, @property & Setters Explained - Python OOP Encapsulation Tutorial #21 by Taught by Celeste AI - AI Coding Coach
Watch full page →Private Attributes, @property & Setters Explained - Python OOP Encapsulation Tutorial
Encapsulation in Python helps protect object data by controlling access to attributes through public, protected, and private conventions. This tutorial covers how to use private attributes with name mangling, and how to implement clean, validated access using the @property decorator and setter methods. You'll also see a practical example with a bank account class demonstrating these concepts.
Code
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Public attribute
self._balance = balance # Protected attribute (convention)
self.__pin = None # Private attribute (name mangling)
@property
def balance(self):
# Read-only property to get balance
return self._balance
@property
def pin(self):
# Getter for private attribute __pin
return self.__pin
@pin.setter
def pin(self, value):
# Setter with validation for pin
if isinstance(value, int) and 1000 <= value <= 9999:
self.__pin = value
else:
raise ValueError("PIN must be a 4-digit integer")
def deposit(self, amount):
if amount > 0:
self._balance += amount
else:
raise ValueError("Deposit amount must be positive")
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
else:
raise ValueError("Invalid withdrawal amount")
# Usage example
account = BankAccount("Alice", 100)
account.pin = 1234 # Set private pin via setter
print(account.balance) # Access balance via property
account.deposit(50)
print(account.balance)
# account.__pin # AttributeError: private attribute not accessible directly
print(account.pin) # Access private pin via getter
Key Points
- Public attributes are accessible from anywhere, while protected and private use underscores to indicate restricted access.
- Private attributes with double underscores are name-mangled to prevent accidental access from outside the class.
- The @property decorator creates getter methods that allow attribute access with dot notation.
- Setter methods with @propertyname.setter enable validation and controlled modification of attributes.
- Encapsulation improves data integrity by hiding implementation details and validating changes through setters.