Methods
Give your objects abilities. Methods are functions that belong to a class.
Code runs right here in your browser. Nothing to install.
Learn it
Methods are functions that belong to an object.
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.
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())
Try it yourself
+10 XPAdd 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.
Capture the flag
+10 XPWhat 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.
Inventory class
+20 XPWrite 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.