Data Hiding in Practice
Bringing together constructors, encapsulation, and access control in real examples.
Introduction
This lesson brings together everything from Week 3 -- constructors, instance and class variables, encapsulation, access modifiers, and getters/setters. We will build two complete, well-designed classes that demonstrate data hiding in action.
Complete Example: Secure Bank Account
class BankAccount:
__total_accounts = 0 # private class variable
def __init__(self, owner, balance=0):
self.__owner = owner
self.__balance = balance
self.__transactions = []
BankAccount.__total_accounts += 1
@property
def balance(self):
return self.__balance
@property
def owner(self):
return self.__owner
def deposit(self, amount):
if amount > 0:
self.__balance += amount
self.__transactions.append(f"+${amount:.2f}")
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
self.__transactions.append(f"-${amount:.2f}")
return True
return False
def get_statement(self):
return self.__transactions.copy()
@classmethod
def get_total_accounts(cls):
return cls.__total_accounts
Using the Secure Account
acc1 = BankAccount("Alice", 1000)
acc2 = BankAccount("Bob", 500)
acc1.deposit(200)
acc1.withdraw(50)
print(acc1.owner) # Alice
print(acc1.balance) # 1150
print(acc1.get_statement()) # ['+$200.00', '-$50.00']
# acc1.__balance = 999999 # This does NOT change the real balance!
# acc1.balance = 999999 # AttributeError — read-only property!
print(BankAccount.get_total_accounts()) # 2
What is Protected Here?
- Balance cannot be set directly -- only through deposit() and withdraw() with validation.
- Owner name is read-only -- once set in the constructor, it cannot be changed.
- Transaction log returns a copy, so the original list cannot be tampered with.
- Total accounts is tracked via a private class variable, accessible only through a class method.
Second Example: Student Record
class StudentRecord:
def __init__(self, name, student_id):
self.__name = name
self.__id = student_id
self.__grades = []
def add_grade(self, grade):
if 0 <= grade <= 100:
self.__grades.append(grade)
else:
print("Grade must be between 0 and 100")
@property
def gpa(self):
if not self.__grades:
return 0.0
return sum(self.__grades) / len(self.__grades)
@property
def name(self):
return self.__name
def display(self):
print(f"{self.__name} (ID: {self.__id}) — GPA: {self.gpa:.1f}")
# Usage
student = StudentRecord("Alice", "STU001")
student.add_grade(85)
student.add_grade(92)
student.add_grade(78)
student.display() # Alice (ID: STU001) — GPA: 85.0
print(student.gpa) # 85.0
student.add_grade(150) # Grade must be between 0 and 100
Week 3 Recap
3.1 __init__ Constructor: Automatically sets up objects with the right data when they are created.
3.2 Instance vs Class Variables: Instance variables are unique per object; class variables are shared by all.
3.3 Encapsulation: Bundles data and methods together, and controls who can access the data.
3.4 Access Modifiers: Public, protected (_), and private (__) naming conventions control visibility.
3.5 Getters and Setters: @property provides clean, controlled access to private data with validation.
3.6 Data Hiding: Combining all of the above to build secure, well-designed classes.
What is Next?
Next week we explore Inheritance -- how classes can share and extend functionality. You will learn to create child classes that reuse code from parent classes, override methods, and use the super() function.
Best Practices
- Design your classes with encapsulation from the start -- it is harder to add later.
- Return copies of mutable data (lists, dicts) to prevent external tampering.
- Use @classmethod for operations that relate to the class as a whole (like counting instances).
- Keep your public interface minimal -- expose only what is necessary.
Common Mistakes
- Returning the actual list instead of a copy -- external code can then modify your internal data.
- Forgetting validation in methods like deposit() and withdraw() -- always check inputs.
- Making everything public "because it is easier" -- this leads to fragile, hard-to-debug code.
Practice Exercises
- Extend the
BankAccountclass with atransfer(other_account, amount)method that withdraws from one account and deposits into another. - Create a
Libraryclass that has a private list of books. Add methods to add a book, remove a book, and search by title. The book list should never be directly accessible. - Create an
Inventoryclass with private stock counts per item. Add methods to add stock, sell items (with validation that stock does not go below zero), and a read-only property for total items in stock.
Summary
- Data hiding combines constructors, private attributes, properties, and validated methods.
- A well-designed class protects its internal state while providing a clean public interface.
- Return copies of mutable data to prevent external tampering.
- Class variables with class methods are great for tracking shared information like object counts.