class, def __init__, and self.field syntax with compile-time safety and zero runtime overhead.
Defining a Class
Declare fields as class-level annotations, then implement__init__ to accept and assign them. The compiler enforces that every field is initialized and that the types match throughout the class body.
Multiple Methods
A class can have as many methods as you need. Each method receivesself as its first parameter, and the compiler enforces that the return type matches the annotation.
Receiver Conventions
The receiver syntax defines ownership and mutation. The compiler does not infer a different convention from the method body.
Use
mut self when a method changes a field or calls another mutable method on the receiver.
Classes in Union Types
Classes are first-class members of union types. Declare a parameter asDog | Cat | Bird and the compiler tracks all three possibilities throughout the function body.
isinstance Narrowing with Multi-Member Unions
When your union has more than two members, useelif chains. The compiler eliminates one variant per branch, leaving only the remaining possibilities.
Hashable Classes
Classes are hashable by default. Callhash() on any instance to get a deterministic integer hash based on its field values.
Error Subclasses
SubclassError to define custom error types for use with Result[T, E]. Error subclasses carry typed fields just like any other class.
Error subclasses carry no hidden stack trace or exception machinery — only the fields you declare. They are lightweight typed values, not exception objects.try/except at the call site:
