1)我无法弄清楚错误:
的位置Error in args[[1]] : subscript out of bounds
来自,如果我尝试运行以下代码:
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)是否可以以这种方式组织代码,我必须只添加一行
.self$var3 <- if(is.null(args[["var3"]])) list() else as.list(args[["var3"]])
用于A类中的initialize函数,其余来自父类Part?
答案 0 :(得分: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))