Programming principles and design · Lesson 29 of 60 · Concept lesson · Optional
Encapsulation
Encapsulation keeps data and the code that works on it together, and controls how outsiders can reach it.
Other code uses a small set of methods instead of changing the data directly.
That way the data can be protected from invalid changes.
Picture it
Code example
class Account {
#balance = 0;
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
get balance() {
return this.#balance;
}
}
const account = new Account();
account.deposit(50);
account.deposit(-20);
console.log(account.balance);Output: 50
The # makes the balance private. deposit rejects the negative amount, so the balance stays 50.
class Account:
def __init__(self):
self._balance = 0
def deposit(self, amount):
if amount > 0:
self._balance += amount
@property
def balance(self):
return self._balance
account = Account()
account.deposit(50)
account.deposit(-20)
print(account.balance)Output: 50
The leading underscore marks the balance as private by habit. deposit rejects the negative amount, so the balance stays 50.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…