Lesson 32 of 34

Methods: What Objects Can Do

10 min 35 XP

Functions written inside a class are called methods. Their first parameter is always self. A method can read and change the object's data.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

With a __str__ method, print(object) shows friendly text.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Challenge

+35 XP

Write a BankAccount class: • __init__: starts with balance = 0 • deposit(amount): adds to the balance • withdraw(amount): subtracts if there is enough, otherwise prints "Insufficient balance" • get_balance(): returns the balance

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.