Python - 25

Python - 25: Working With Multiple Objects

Classes become more useful when you create several objects and store them together in a list.

Your challenge: Create several objects, place them in a list, then loop through the list and call a method on each object.

✦ Python Editor
▶ Output

Create multiple objects

Each object can use the same class but store different values.

For example: enemy1 = Enemy("Goblin", 50)

Store objects in a list

Objects can be stored just like strings or numbers: enemies = [enemy1, enemy2, enemy3]

Loop through the objects

Use a for loop to visit each object in the list.

Then call its method: enemy.show_enemy()

Try it: Add a fourth enemy with a different name and health value.

Good Python habit: When several objects belong to the same group, storing them in a list makes them easier to process together.

👀 Show Example Solution
class Enemy:

    def __init__(self, name, health):
        self.name = name
        self.health = health

    def show_enemy(self):
        print("Enemy:")
        print(self.name)

        print("Health:")
        print(self.health)

        print("---")

enemy1 = Enemy("Goblin", 50)
enemy2 = Enemy("Skeleton", 75)
enemy3 = Enemy("Dragon", 300)

enemies = [enemy1, enemy2, enemy3]

for enemy in enemies:
    enemy.show_enemy()

The list stores several Enemy objects, and the loop calls the same method on each one.