R Reference Class multiple inheritance: how to call method in a specific parent class?

空扰寡人 提交于 2019-12-06 21:16:27

I'm not a heavy reference class user, but in S4 (on which reference classes are based) the best approach is often to avoid defining initialize methods (which have a complicated contract, both 'initialize' and 'copy' of named and unnamed arguments), to treat the constructor returned by setClass() as for internal use only, and to provide a user-facing constructor. Thus

.SuperA <- setRefClass("SuperA", fields = list(a = "ANY"))

.SuperB <- setRefClass("SuperB", fields = list(b = "ANY"))

.Child <- setRefClass("Child", contains = c("SuperA", "SuperB"))

Child <- function(a, b)
    ## any coercion, then...
    .Child(a=a, b=b)

The result is

> Child(a=1, b=2)
Reference class object of class "Child"
Field "b":
[1] 2
Field "a":
[1] 1

From ?ReferenceClasses, the method $export(Class) coerces the object to an instance of 'Class', so

.SuperA <- setRefClass("SuperA", fields = list(a = "ANY"),
    methods=list(foo=function() .self$a))

.SuperB <- setRefClass("SuperB", fields = list(b = "ANY"),
    methods=list(foo=function() .self$b))

.Child <- setRefClass("Child", contains = c("SuperA", "SuperB"),
    methods=list(foo=function() {
        c(export("SuperA")$foo(), export("SuperB")$foo())
    }))

Child <- function(a, b)
    .Child(a=a, b=b)

Leads to

> Child(a=1, b=2)$foo()
[1] 1 2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!