Legends ofPythos
Claim your name
Objects and Classes

Why classes exist

Lesson 1 of 13

Watch the lesson5:29 · 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 dictionary 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 only loosely connected.

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 change the data the wrong way.

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

ada = Player('Ada')
ada.take_damage(30)
print(ada.hp)   # 70
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. The last three lines make a player called Ada, take 30 off her HP, and print 70.

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.
# .upper() works on s's own characters:
s = 'hello'
print(s.upper())   # HELLO

# A list stores items, and has methods too.
# .append() changes tasks itself:
tasks = ['a', 'b']
tasks.append('c')
print(tasks)       # ['a', 'b', 'c']
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 the key 'count' set to 0, and increment(c), which adds 1 to c['count'] in place.

Then, after the two functions, make one counter named c with make_counter(), call increment(c) three times, and print c['count']. It should print 3. Print nothing else.
def make_counter():
    pass


def increment(c):
    pass

Run your code to check it against the tests.