Encapsulation
โ Report an issue with this lessonEncapsulation means an object controls access to its own data, instead of letting any code reach in and set it to something invalid.
class BankAccount:
def __init__(self, balance):
self._balance = balance # convention: "protected" by leading underscore
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
@property
def balance(self):
return self._balance
Python doesn't enforce privacy the way Java does โ the leading
underscore is a convention, not a lock. The @property
decorator lets you expose account.balance as read-only,
computed from a method, without the caller knowing it's not a plain
attribute.
Try it yourself
Exercise: Complete the BankAccount class below: deposit(amount) should raise ValueError if amount is not positive, otherwise add it to _balance. Add a read-only balance property using @property. Then deposit 50 into an account starting at 100 and print account.balance.
Expected output:
150
Run your code and get it working before marking this lesson complete.
// that was the last free lesson
8 more lessons โ including Project: build a small shape library โ plus a certificate are waiting.
Unlock the full course โ $59.99