Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

4. Classes

A class bundles data (fields) with behaviour (methods).

Defining a class

class Dog:
    fn init(self, name):
        self.name = name

    fn bark(self):
        return self.name + " says woof"

d = Dog("Rex")
print(d.bark())
# => Rex says woof

Two things to notice:

  • The first parameter of every method is self — the instance the method was called on. It is a normal parameter name, not magic.
  • init is the constructor. You call the class itself (Dog("Rex"), no new) and Korrin runs init for you.

Fields

Fields come into being when you assign to self.something, usually in init. Reading a field that was never set is an error:

class Box:
    fn init(self, value):
        self.value = value

b = Box(42)
print(b.value)
b.value = 99
print(b.value)
# => 42
# => 99

Inheritance

class Child(Parent): inherits Parent's methods. A method on the child with the same name overrides the parent's:

class Animal:
    fn init(self, name):
        self.name = name

    fn sound(self):
        return "some noise"

    fn describe(self):
        return self.name + " makes " + self.sound()

class Cat(Animal):
    fn sound(self):
        return "a meow"

print(Cat("Whiskers").describe())
# => Whiskers makes a meow

Notice describe is defined only on Animal, but calling it on a Cat still uses Cat's sound.

super

Inside a method, super.method(...) calls the parent's version — useful when you want to extend behaviour rather than replace it:

class Vehicle:
    fn init(self, wheels):
        self.wheels = wheels

    fn describe(self):
        return str(self.wheels) + " wheels"

class Car(Vehicle):
    fn init(self, brand):
        super.init(4)
        self.brand = brand

    fn describe(self):
        return self.brand + ", " + super.describe()

print(Car("Volvo").describe())
# => Volvo, 4 wheels