Skip to content
FollowtheDamnCode

Classes and Objects

Blueprints, __init__, self, and methods.

6 minute read

Big idea

A class is a blueprint; an object is a thing built from it. The class says what data each object holds (attributes) and what it can do (methods).

Your first class

A Dog class, and two dogs
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says woof!")

rex = Dog("Rex", 3)
fido = Dog("Fido", 7)
rex.bark()
fido.bark()
print(rex.age + fido.age)
output
Rex says woof!
Fido says woof!
10

Run and edit it in the app.

Piece by piece:

  • class Dog: — defines the blueprint. Class names use CapitalWords.
  • __init__ — the initialiser. It runs automatically when you create an object, and sets up its attributes.
  • self — the object being worked on. self.name = name stores the name on that object.
  • def bark(self): — a method: a function that belongs to the class. It gets the object as self.
  • Dog("Rex", 3) — creates a new object. Python passes it to __init__ as self, with "Rex" and 3 as the other arguments.

Each object has its own data

One class, many objects

Methods that change the object

Predict: a counter object
class Counter:
    def __init__(self):
        self.count = 0

    def click(self):
        self.count += 1

    def reset(self):
        self.count = 0

a = Counter()
b = Counter()
a.click()
a.click()
b.click()
print(a.count, b.count)
a.reset()
print(a.count, b.count)
What does it print? Show the answer
2 1
0 1

Run and edit it in the app.

a and b are separate objects, each with its own count.

Forgetting self

Fix the bug: the balance should go up to 150
class Account:
    def __init__(self, balance):
        self.balance = balance

    def deposit(self, amount):
        balance = self.balance + amount

acct = Account(100)
acct.deposit(50)
print(acct.balance)
output
150

Run and edit it in the app.

balance = ... makes a local variable inside the method, which vanishes when it returns. To change the object's attribute, assign to self.balance.

Class attributes

A variable written directly in the class body is shared by all objects:

class Dog:
    species = "Canis familiaris"   # same for every dog
    def __init__(self, name):
        self.name = name           # different for each dog

In def bark(self): what is self?

Watch it

Think of it like

A cookie cutter (the class) and the cookies (objects). Every cookie has the same shape, but each can have its own icing — its own attribute values.

Key terms

  • Class — A blueprint for objects.
  • Object (instance) — One thing made from a class.
  • __init__ — Sets up a new object's attributes.
  • self — The object a method is working on.

Check yourself

When does __init__ run?

Inside a method, how do you store a value on the object?

a = Counter(); b = Counter(). Do a and b share attributes set in __init__?