R参考Class多重继承:如何在特定parentclass中调用方法?

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

我有一个参考 class Child,它继承自 parents SuperASuperB。在Childinitialize方法中,我想依次调用SuperASuperBinitialize方法。

因此,例如,我有:

SuperA <- setRefClass("SuperA",
    fields = list(a = "ANY"),
    methods = list(
        initialize = function(a) {
            print(a)
            initFields(a = a)
        }
    )
)

SuperB <- setRefClass("SuperB",
    fields = list(b = "ANY"),
    methods = list(
        initialize = function(b) {
            print(b)
            initFields(b = b)
        }
    )
)

Child <- setRefClass("Child",
    contains = c("SuperA", "SuperB"),
    methods = list(
        initialize = function(a, b) {
            # attempt to invoke parent constructors one by one:
            SuperA$callSuper(a)
            SuperB$callSuper(b)
        }
    )
)

Child(1, 2)   # want values 1 and 2 to be printed during construction of superclasses

然而我得到的是:

Error in print(a) : argument "a" is missing, with no default 

那么有没有人对如何调用属于特定 parent 的方法有任何想法?

我不是重度引用 class 用户,但在 S4(引用 classes 所基于的)中,最好的方法通常是避免定义初始化方法(它有一个复杂的合同,命名和未命名参数的 'initialize' 和 'copy'),将 setClass() 返回的构造函数视为仅供内部使用,并提供面向用户的构造函数。于是

.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)

结果是

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

?ReferenceClasses开始,方法$export(Class)将对象强制转换为'Class'的实例,所以

.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)

导致

> Child(a=1, b=2)$foo()
[1] 1 2