Methods

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What are Methods?

You know how to store data in objects with attributes. But objects can also do things! A method is a function defined inside a class. Just like `"hello".upper()` calls the `upper()` method on a string, you can create your own methods.

class Codemon: def __init__(self, name, level=1): self.name = name self.level = level def greet(self): print(f"Hi! I'm {self.name}!") myCdm = Codemon("Aquachu") myCdm.greet()

`greet` is a method. Just like `__init__`, it takes `self` as the first parameter. We call it with `myCdm.greet()` — Python automatically passes `myCdm` as `self`.

Exercise 2 — Methods use self

Inside a method, `self` gives you access to all the object's attributes. This is how methods know which Codémon they're working with.

class Codemon: def __init__(self, name, level=1): self.name = name self.level = level def level_up(self): self.level += 1 print(f"{self.name} is now level {self.level}!") myCdm = Codemon("Pyrochu", 10) myCdm.level_up() myCdm.level_up()

`level_up()` reads `self.name` and modifies `self.level`. The changes are permanent — the object keeps the new level.

Exercise 3 — Methods with Parameters

Methods can take extra parameters, just like regular functions. The only difference is that `self` is always first.

class Codemon: def __init__(self, name, level=1): self.name = name self.level = level def attack(self, target): print(f"{self.name} attacks {target.name}!") target.level -= 1 a = Codemon("Aquachu", 10) p = Codemon("Pyrochu", 8) a.attack(p) print(f"{p.name}: Level {p.level}")

Here `attack` takes another Codémon object as a parameter. One object can interact with another!

Exercise 4 — Define a Method

Complete the method that heals the Codémon by a given amount.

Hint : Every method's first parameter is `self`. The method needs to modify the HP attribute.

Exercise 5 — Calling a Method

What does this code print?

class Codemon: def __init__(self, name, hp=100): self.name = name self.hp = hp def take_damage(self, amount): self.hp -= amount myCdm = Codemon("Florachu") myCdm.take_damage(30) print(myCdm.hp)
Options
• 100
• 70
• 30
• Error

Hint : `take_damage(30)` subtracts 30 from the starting HP of 100.

Exercise 6 — Method with Parameter

Complete the method to transfer HP from one Codémon to another.

Hint : The `target` is the other Codémon receiving the HP. The `amount` is how much to add.

Exercise 7 — Methods that Return Values

Methods can also return values, just like functions. Use the `return` keyword.

class Codemon: def __init__(self, name, level=1, hp=100): self.name = name self.level = level self.hp = hp def power(self): return self.level * 10 + self.hp myCdm = Codemon("Rockachu", 15, 120) print(f"Power: {myCdm.power()}")

`power()` calculates and returns a value. It doesn't modify the object — it just computes something from its attributes.

Exercise 8 — Return from Method

What does this code print?

class Codemon: def __init__(self, name, level=1): self.name = name self.level = level def is_evolved(self): return self.level >= 20 myCdm = Codemon("Metachu", 25) print(myCdm.is_evolved())
Options
• True
• False
• 25
• Error

Hint : `is_evolved()` checks if the level is 20 or more and returns a boolean.

Exercise 9 — The __str__ Method

When you `print()` an object, Python shows something ugly like `<__main__.Codemon object>`.

class Codemon: def __init__(self, name, element, level=1): self.name = name self.element = element self.level = level myCdm = Codemon("Aquachu", "Water", 15) print(myCdm)

You can fix this by defining the `__str__` method — it tells Python how to convert your object to a string.

class Codemon: def __init__(self, name, element, level=1): self.name = name self.element = element self.level = level def __str__(self): return f"{self.name} ({self.element}) - Lv.{self.level}" myCdm = Codemon("Aquachu", "Water", 15) print(myCdm)

Now `print(myCdm)` shows something readable! `__str__` must return a string (not print it).

Exercise 10 — Define __str__

Complete the `__str__` method to display the Codémon nicely.

Hint : The special method for string representation starts and ends with double underscores. To print an object, you pass the variable to `print()`.

Exercise 11 — Methods Vocabulary

Match each piece of code with its description.

Items to match
• `def method(self):`
• `def method(self, x):`
• `self.attribute`
• `return value`
• `__str__(self)`
Definitions
• A method with no extra parameters
• A method with one extra parameter
• Access the object's data inside a method
• Give back a result from a method
• Controls how print() displays the object

Exercise 12 — Codémon Battle Methods

Add methods to the Codémon class: 1. `attack(self, target)` — reduces target's HP by `self.level * 2`. Print `"X attacks Y!"` 2. `is_alive(self)` — returns `True` if HP > 0 3. `__str__(self)` — returns `"Name (Lv.X) - HP: Y"` 4. Create 2 Codémon, have them attack each other, then print both

Starter code
class Codemon: def __init__(self, name, level=1, hp=100): self.name = name self.level = level self.hp = hp # Add attack method # Add is_alive method # Add __str__ method # Create 2 Codémon and battle!
Back to the course