Browser lab18 min+60 XP

Methods

Give your objects abilities. Methods are functions that belong to a class.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Methods are functions that belong to an object.

Key words
nova: one Hero object (data + methods)name"Nova"health100, then 70is_alive()returns Truetake_hit(30)a methodnova.take_hit(30)changes
An object holds data and methods. Calling take_hit changes health.

A method is a function defined inside a class. It always takes self first, so it can read and change that object's attributes. You call it with a dot: nova.heal(20).

Methods keep the data and the code that works on it together. Instead of a separate function that needs to be passed a hero, the hero knows how to heal itself.

Methods can return values too, like is_alive() returning True or False.

Real life linkA car has things it can do: start, brake, sound the horn. Methods are the things an object can do.
Example code
class Hero:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def take_hit(self, damage):
        self.health = max(self.health - damage, 0)
        print(f"{self.name} takes {damage} damage. HP: {self.health}")

    def is_alive(self):
        return self.health > 0

nova = Hero("Nova")
nova.take_hit(30)
nova.take_hit(80)
print("Alive?", nova.is_alive())
TASK 2

Try it yourself

+10 XP

Add two methods to BankAccount: deposit(amount) adds money, and withdraw(amount) takes money out only if there is enough, otherwise prints Not enough money. Run the test code to get Balance: 70.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What do we call a function that is defined inside a class?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Inventory class

+20 XP

Write a class Inventory with a max_items limit (default 3). Methods: add(item) (print Bag full if at the limit), remove(item) (print You do not have that if missing), has(item) returning True or False, and show() printing Bag: torch, map. Test every method.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.