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

7. Classes

class_definition =
    "class" , NAME , [ "(" , NAME , ")" ] , ":" , NEWLINE ,
    INDENT , class_member , { class_member } , DEDENT ;
class_member = function_definition | ( "pass" , NEWLINE ) ;

A class body contains only method definitions (and pass). It binds the class name in the current scope when it executes.

7.1 Methods and self

A method is a fn in a class body. Its first parameter — conventionally named self — receives the instance the method was called on (ADR 0005). self is an ordinary parameter, not a keyword.

class Point:
    fn init(self, x, y):
        self.x = x
        self.y = y

    fn manhattan(self):
        return self.x + self.y

p = Point(3, 4)
print(p.manhattan())
# => 7

7.2 Construction

Calling a class constructs an instance: a new empty instance is created, then, if the class has a method named init, it is called with the instance as self and the remaining arguments. There is no new keyword.

If a class has no init, calling it with any argument is E0303.

7.3 Fields

Fields are created by assignment to self.name (usually in init). Reading a field or method that does not exist is E0309. Fields shadow methods of the same name.

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

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

7.4 Inheritance

class Child(Parent): makes Parent the superclass. Method lookup checks the class, then its parent, then the grandparent, and so on. Milestone 1 has single inheritance only. A class that names itself as parent is E0208.

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

    fn noise(self):
        return "..."

    fn speak(self):
        return self.name + " says " + self.noise()

class Dog(Animal):
    fn noise(self):
        return "woof"

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

7.5 super

Inside a method of a class with a parent, super.method(args) calls the parent's version of method, bound to the current self. super outside a method is E0205; super in a class with no parent is E0206. Both are reported before the program runs.

class Base:
    fn init(self, x):
        self.x = x

    fn show(self):
        return "x=" + str(self.x)

class Derived(Base):
    fn init(self, x, y):
        super.init(x)
        self.y = y

    fn show(self):
        return super.show() + " y=" + str(self.y)

print(Derived(1, 2).show())
# => x=1 y=2