Course outline · 0% complete

0/27 lessons0%

Course overview →

Classes and __init__

lesson 3-1 · ~13 min · 7/27

Quiz

Warm-up from lesson 2-2: what is wrong with def register(user, users=[])?

When a dict is not enough

Almost every large Python codebase, from web frameworks to data libraries to the standard library itself, is organized around classes, so this unit is where your code starts to look like a working engineer's. The motivation is concrete.

In Python for Beginners you modeled things with dicts: player = {"name": "mia", "score": 0}. That works until you have behavior that belongs to the data. Where should the code that levels a player up live? Copy-pasted functions that all take a dict? Messy.

A class bundles data and behavior into one unit. It is a blueprint. Each value stamped from the blueprint is an object (or instance) with its own data:

class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

__init__ is the initializer: Python calls it automatically when you write Player("mia"). self is the object being created, and self.name = name stores data on that object as an attribute.

class Playerthe blueprintPlayer("mia")name = "mia"score = 0Player("leo")name = "leo"score = 0
One class, many instances. Each instance carries its own attribute values, created by __init__.

Code exercise · python

Run this program. Notice mia and leo each keep their own score. Changing one never touches the other.

Code exercise · python

Your turn. Write a Book class whose __init__ takes title and pages and stores both as attributes. Create the two books shown and print each one's title and pages.

Code exercise · python

Your turn. __init__ can compute attributes, not just store parameters. Write Circle so it stores radius AND computes self.diameter (radius * 2) at creation time. Create Circle(5) and print both attributes on one line.

Quiz

In p = Player("mia"), when does __init__ run?