gpt4 book ai didi

r - 如何使用引用类在 R 的父类中设置字段?

转载 作者:行者123 更新时间:2023-12-02 00:07:34 25 4
gpt4 key购买 nike

我正在尝试设置 params 字段并在 Template 类中对其进行验证,因此我可以执行 TemplateClass$new(params) 并且它会自动验证,但是我得到一个错误:

Template <- setRefClass('Template',
fields = c(
"params"
),

methods = list(
initialize = function(params){
params <<- params
validate_params()
},
validate_params = function(){
"everything okay"
}
)
)

PointsTemplate <- setRefClass('PointsTemplate',

contains = "Template",

methods = list(
initialize = function(params){
callSuper(params)
}
)
)

Error in .Object$initialize(...) :
argument "params" is missing, with no default

编辑:我似乎已经通过将 Template 类中的 initialize 方法更改为 initialize = function(params = NULL){}。但我不明白为什么需要这样做。

此外,我还看到其他人在类不包含任何父类(super class)时使用 callSuper()。这是什么原因?

最佳答案

我对 R 引用类没有任何经验,但借助 ?ReferenceClasses 您可以阅读以下内容:

Initialization methods need some care in design, as they do for S4 classes. Therefore, your method should normally include ... as an argument, all other arguments should have defaults or check for missingness, and your method should pass all initialized values on via $callSuper() or $initFields() if you know that your superclasses have no initialization methods.

所以我通过在父类中设置我的初始化函数来理解这一点,使用 ... 并为所有具有默认值的字段命名参数。

Template <- setRefClass('Template',
fields = list(params="list"),
methods = list(initialize =
function(...,params=list(1:5)){
callSuper(...,params=params)
validate_params()
},
validate_params = function(){
"everything okay"
}
)
)

对于子类不需要初始化参数,因为我相信父类(super class)会点它。

PointsTemplate <- setRefClass('PointsTemplate',
contains = "Template",
methods = list(initialize =
function(...){
callSuper(...)
}

))

不测试初始化​​:

## using default values
> PointsTemplate$new()
Reference class object of class "PointsTemplate"
Field "params":
[[1]]
[1] 1 2 3 4 5
## setting params
PointsTemplate$new(params=list(1:10))
Reference class object of class "PointsTemplate"
Field "params":
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10

关于r - 如何使用引用类在 R 的父类中设置字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17308343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com