0

1) I cant figure out where the Error:

Error in args[[1]] : subscript out of bounds

comes from, if I try to run the folowing code:

Part.initialize<-function(...){
  args<-list(...)

    .self$var1 <- if(is.null(args[["var1"]])) vector() else args[["var1"]]
    .self$var2 <- if(is.null(args[["var2"]])) character() else as.character(args[["var2"]])
    .self
}

Part<-setRefClass(Class = "Part"
                 ,fields = c(var1 = "ANY", var2 = "character")
                 ,methods = list(initialize=Part.initialize))

A.initialize<-function(...){
  args<-list(...)

  .self$var1 <- if(is.null(args[["var1"]])) vector() else args[["var1"]]
  .self$var2 <- if(is.null(args[["var2"]])) character() else as.character(args[["var2"]])
  .self$var3 <- if(is.null(args[["var3"]])) list() else as.list(args[["var3"]])
  .self  
}

A<-setRefClass(Class = "A"
              ,contains = "Part"
              ,fields = list(var3 = "list")
              ,methods = list(initialize=A.initialize))

2) Is it possible to organize the code in that way that I have to add only one line

.self$var3 <- if(is.null(args[["var3"]])) list() else as.list(args[["var3"]])

for the initialize function in class A and the rest comes from the father class Part?

4

1 回答 1

1

使用命名参数而不是解析...;确保在没有参数的情况下调用默认构造函数

Part.initialize<-function(..., var1=vector(), var2=character()){
    callSuper(..., var1=var1, var2=as.character(var2))
}

Part<-setRefClass(Class = "Part"
                 ,fields = c(var1 = "ANY", var2 = "character")
                 ,methods = list(initialize=Part.initialize))

只解释正在考虑的类的论点

A.initialize<-function(..., var3=list()){
    callSuper(..., var3=as.list(var3))
}

A<-setRefClass(Class = "A"
               ,contains = "Part"
               ,fields = list(var3 = "list")
               ,methods = list(initialize=A.initialize))

简单的测试用例

Part()
A()
A(var3=list(a=1))
于 2013-09-21T12:46:22.547 回答