RUNTIME VALUE CONVERSIONS
Convert basic classes with explicitly declared fields, a constructor, and ordinary instance methods. Runtime value conversion preserves shared instance identity.
class Counter:
name: str
value: int
def __init__(self, name: str, value: int) -> None:
self.name = name
self.value = value
def add(self, amount: int) -> int:
self.value += amount
return self.value
def advance(counter: Counter, amount: int) -> Counter:
counter.add(amount)
return counter
def main() -> int:
counter = Counter("jobs", 2)
same = advance(counter, 3)
add_more = same.add
print(add_more(1), counter.value, counter is same)
return 0
The program prints 6 6 True. The function parameter, result, and local aliases refer to the same instance. The stored bound method retains its receiver.
Declare each field in the class body as name: type, without a class-level initializer. Assign instance values through self.name in __init__, and initialize every field before it is read. Fields can hold supported scalar, union, list, tuple, dictionary, object, or declared-class values.
Field assignment checks the declared type. An assignment such as counter.value = "three" fails the integer field check. Reading an uninitialized field, creating an undeclared attribute, or accessing an unknown method reports a runtime error.
A container field checks its current elements when the field is assigned. Mutating the container itself is separate from replacing the field; container annotations do not permanently constrain writes through aliases.
Use self as the first positional method parameter. Remaining parameters support defaults, keyword calls, positional-only markers, and keyword-only markers under the function binding rules. Methods can read or update fields, call other supported functions, and return admitted values. Store or pass an ordinary bound method just like a function value.
Bound methods compare equal when they refer to the same instance and the same underlying method. Different receivers or methods remain distinct. Instances can be passed to functions, returned, and stored in supported containers.
__init__, including keywords and defaults.__init__; properties, static/class methods, operator protocols, and other special methods are unsupported.For immutable records with direct typed conversion, use Simple immutable records.