Class-based Generative Functions
Overview
In the first section on Generative Functions, the fastest way to create them was introduced: using the decorator. However, if you’re working in an Object-Oriented Programming (OOP) environment or need to store state that persists across evaluations of the Generative Function, you can define a one as a class instead.
Creating a class-based Generative Function
To create a class-based Generative Function, subclass GenerativeFunction
directly.
This approach requires gathering all inputs into one Generative Type and all outputs into another.
You can also override the __init__
method (executed when the Function Server starts),
which can be helpful for initializing values or preventing repeated computations.
Here, GenerativeFunction
is imported from generative.core
,
and is subclassed to create the Generative Function.
The input and output type are specified as type parameters to GenerativeFunction
in square brackets.
You don’t need to fully understand this syntax,
but you can learn more about Python’s type parameters from the Python guide.
Each GenerativeFunction
must have a run
method defined, with exactly two arguments.
The first argument is self
, and the second argument is a Generative Type.
If the init method is overridden, the parent init method must be called using super().__init__()
.
Any variables assigned in the __init__
method are available in the run
method.
Under the hood,
Generative Functions created by decorating a Python function
are converted into class-based Generative Functions with run
methods.
While this doesn’t impact functionality, it may explain occasional behavior or error messages.