Classes
A class is a blueprint and an object is a thing built from it. __init__ runs when an object is created and stores its data on self:
class Dog: def __init__(self, name, age): self.name = name self.age = age
rex = Dog("Rex", 3) rex.name # "Rex"
self is the new object, passed automatically to the method. Store persistent attributes with self.name = name; assigning only name = name does not store anything on the object. Arguments to Dog("Rex", 3) supply name and age, not self.
See it run
class Dog: def __init__(self, name): self.name = name self.tricks = 0 rex = Dog("Rex") fido = Dog("Fido") rex.tricks = 2 print(rex.tricks, fido.tricks)
The class is the blueprint. Each Dog(...) builds a separate object on the right.
Practice classes
Exercise 1
Create a class Pet whose __init__ takes name and species and stores both. Then make my_pet = Pet("Rex", "dog").
Exercise 2
Create Parcel(label, weight, fragile=False) storing all three attributes per instance. Make box = Parcel("Books", 4) and glass = Parcel("Vase", 1, True).
Exercise 3
Create Reading(sensor, values) storing sensor and an independent list copy of values. Make raw = [12, 14] and sample = Reading("roof", raw), then append 99 to raw. The reading must retain its original snapshot; separate readings must not share lists.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.