Legends ofPythos
Claim your name
Objects and Classes

Why classes exist

Lesson 1 of 13

Watch the lesson1:02 · with Torsten
Imagine tracking a player in a game: their name, health points (HP), and level. You could store these as separate variables or inside one dictionary:

player = {'name': 'Ada', 'hp': 80, 'level': 3}

Then you write functions that take this dict everywhere:

def attack(player): player['hp'] -= 10

It works… until the code grows. You start passing player, then maybe also a separate list of their skills and another function for damage calculation, all loosely coupled.

The problem with loose data

When related data (name, HP) and the behaviours that act on it (attacking, healing) live in separate places, you must remember to keep them in sync. It's easy for one function to forget a field or mutate data incorrectly.

A class bundles both together into one unit: an object.

What a class gives you

class Player:
    def __init__(self, name):
        self.name = name
        self.hp = 100
        self.level = 1

    def take_damage(self, amount):
        self.hp -= amount
A simple Player class (conceptual preview)
__init__ runs when you create an object and sets up its starting state. Methods like take_damage live with the data they modify — no extra arguments needed to find where HP is stored.

You've actually been using this pattern without knowing it: strings and lists are objects of built-in classes.
# A string has methods attached to its data
s = 'hello'
print(s.upper())   # HELLO — the method acts on s's own characters

# A list stores items AND provides operations
tasks = ['a', 'b']
tasks.append('c')  # no need to pass tasks around separately
Strings and lists already behave like class instances

Your turn

0 of 2 solved

Exercise 1

+30 XP
Write a function is_string_instance(value) that returns True if the argument is an instance of the built-in str class, and False otherwise. Use Python's isinstance() check with (value, str). Test it mentally: 'hi' should give True; 42 should give False.
def is_string_instance(value):
    pass

Run your code to check it against the tests.

Exercise 2

+30 XP
Define two functions: make_counter() which returns a dictionary with key 'count' set to 0, and increment(counter) which adds 1 to counter['count'] in place.

Then, after the function definitions, create one counter named c using make_counter(), call its increment three times (i.e. increment(c) three times), and print(c['count']). The expected output when graded will be '3'.
def make_counter():
    pass


def increment(c):
    pass

Run your code to check it against the tests.