In R6, How can I get the full list of class inheritances, without creating instances of the generator objects?
Consider the following:
A = R6::R6Class("Base",NULL)
B = R6::R6Class("Top",inherit = A)
class(B) #Returns 'R6ClassGenerator'
B$classname #Returns 'Top'
What I want is c('Top','Base','R6')
In other words, what would otherwise be returned by class(B$new())
In the real world, I have a complex set of inheritances, and, initializers with many arguments, some without default values, so I am trying to avoid instantiating a new object in order to obtain this information.
There isn't a built-in way to find all the classes that B inherits without calling B$new()
. This is because inheritance is determined when objects are instantiated, not when the classes are created. A class (AKA generator object) knows the name of the class it inherits from, but that name is evaluated only when objects are instantiated.
You could do something like this to find the inheritance chain, but this uses some internal APIs that could possibly change in the future (although they probably won't):
findClasses <- function(x) {
if (is.null(x))
return(NULL)
parent <- x$get_inherit()
c(x$classname, findClasses(parent))
}
A <- R6::R6Class("Base",NULL)
B <- R6::R6Class("Middle", inherit = A)
C <- R6::R6Class("Top", inherit = B)
findClasses(C)
#> [1] "Top" "Middle" "Base"
来源:https://stackoverflow.com/questions/37303552/r-r6-get-full-class-name-from-r6generator-object