Introduction
So far, you have learned how to:
- Create classes and objects
- Store data using attributes
- Write methods that change an object’s state
In this lesson, we will take the next step.
Instead of using methods on their own, you will learn how:
- Multiple methods can work together
- An object can behave like a small system
- State changes can build up over time
By the end of this lesson, your objects will feel more like real things rather than just containers for data.
Objects as Mini-Systems
A mini-system is an object that:
- Stores data
- Has multiple behaviours (methods)
- Updates itself based on actions
For example, a game character might:
- Lose health when damaged
- Gain health when healed
- Check whether it is still alive
All of this logic can live inside one class.
Example: A Simple Game Player
class Player:
def __init__(self, name):
self.name = name
self.health = 100
def take_damage(self, amount):
self.health -= amount
def heal(self, amount):
self.health += amount
def show_health(self):
print(self.health)
Each method:
- Does one clear job
- Updates or uses the same data
- Works together with the others
Predict:
Look at the code below. What do you think will be printed?
class Player:
def __init__(self, name):
self.name = name
self.health = 100
def take_damage(self, amount):
self.health -= amount
def heal(self, amount):
self.health += amount
player = Player("Alex")
player.take_damage(30)
player.heal(10)
player.take_damage(20)
print(player.health)
Think about:
- What is the starting value of
health? - How does each method change it?
- Does the order of method calls matter?
Run:
Run the program below to check your prediction.
Investigate:
Now let’s explore how methods can be chained together to control behaviour.
Try this:
- Add a method called
is_alive - If health is greater than 0, print
"Alive" - Otherwise, print
"Game Over"
Use the editor below to experiment.
Think about:
- Why is this check inside a method?
- What would happen if we checked health outside the class?
Modify:
The following program is meant to reduce health and then check if the player is alive, but it does not work correctly.
Fix the code so the logic works as intended.
The problem
- The health value is not updated
selfis missing inside the condition