Encapsulation means keeping data safe inside the object. Methods control how data is accessed and modified.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print('Insufficient funds!')
else:
self.balance -= amount
📋 Instructions
Create a `BankAccount` class with:
- `__init__(self, owner, balance=0)`
- `deposit(amount)` — adds to balance, prints new balance
- `withdraw(amount)` — subtracts if sufficient funds
- `get_balance()` — returns the balance
Test:
```python
acc = BankAccount('Alice', 1000)
acc.deposit(500)
acc.withdraw(200)
acc.withdraw(2000)
print(f'Balance: ${acc.get_balance()}')
```
Expected output:
```
Deposited $500. New balance: $1500
Withdrew $200. New balance: $1300
Insufficient funds!
Balance: $1300
```
Create a BankAccount class with __init__(self, owner, balance=0). Add methods deposit(amount) and withdraw(amount). Check if enough balance before withdrawing!
⚠️ Try solving it yourself first — you'll learn more!
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print('Insufficient funds!')
else:
self.balance -= amount