R6Point1Class | R Documentation |
Elements in static
can be called without instantiation, e.g. Class$method()
.
Functions are evaluated in the environment of Class
, so you can refer to self
(which is the class—not the instance—here) to create class methods.
R6Point1Class(..., static = NULL)
... |
Passed through to R6::R6Class |
static |
A named list of static/class functions/values to turn into
methods/attributes. Note there is currently no differentiation between static
and class methods at the moment; static methods are simply class methods that
do not access |
Sometimes we want static/class methods/attributes that can be accessed from
the class (e.g. MyR6Class$my_static_method()
) instead of an instance of
that class (e.g. MyR6Class$new(...)$my_normal_method()
). As individual
classes are environments, these can be added after the fact like so:
MyR6Class <- R6Class(...) MyR6Class$my_static_method <- function(x) ...
But the problem with the above is it's not heritable; if you make a class that
inherits from MyR6Class
, it will not have $my_static_method()
unless you
manually re-add it.
This class structure abstracts the pattern, so when you create a new class, it
checks if the parent contains anything in private$static
, and copies over any
methods/attributes there, less any overwritten in the new class.
There are lots of reasons you may want static/class methods/attributes, but
the immediate use-case here is to create alternate methods for instantiating
a class besides $new()
/$initialize()
. For instance, if a class can be
represented as JSON, it's quite helpful to have a $from_json()
method that
can recreate an instance from a JSON blob.
You could have a separate special reader function that returns an instance, but especially as classes multiply this solution becomes difficult to maintain.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.