R,R6,从R6Generator对象获取完整的类名 [英] R, R6, Get Full Class Name from R6Generator Object
问题描述
在R6中,如何在不创建生成器对象实例的情况下获取类继承的完整列表?
In R6, How can I get the full list of class inheritances, without creating instances of the generator objects?
请考虑以下内容:
A = R6::R6Class("Base",NULL)
B = R6::R6Class("Top",inherit = A)
class(B) #Returns 'R6ClassGenerator'
B$classname #Returns 'Top'
我想要的是 c('Top','Base','R6')
换句话说,在现实世界中, class(B $ new())
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.
推荐答案
没有一种内置方法来查找B继承的所有类而无需调用 B $ new()
。这是因为继承是在实例化对象时确定的,而不是在创建类时确定的。一个类(AKA生成器对象)知道它所继承的类的 name ,但是仅在实例化对象时才对该名称进行评估。
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.
您可以执行以下操作来找到继承链,但这使用了一些将来可能会更改的内部API(尽管它们可能不会更改):
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"
这篇关于R,R6,从R6Generator对象获取完整的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!