S4构造函数初始化和原型 [英] S4 constructor initialize and prototype

查看:79
本文介绍了S4构造函数初始化和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在构造函数中调用validity方法来构建S4对象。

I am trying to build a S4 object by calling the validity method in the constructor.

setClass("Person", slot = c(Age = "numeric"))

validityPerson<-function(object){
    if(object@Age < 0)return("Age cannot be negative")
TRUE
}
setValidity("Person", validityPerson)
setMethod("initialize","Person", function(.Object,...){
validObject(.Object)
.Object
})

此代码有问题,因为我得到了

This code is problematic because I get

new("Person", Age = 12)
#Error in if (object@Age < 0) return("Age cannot be negative") : 
#argument is of length zero

当然,我希望年龄等于12。这是一个玩具示例,但我试图了解如何拥有一个可能会进行其他所有初始化操作的初始化方法,然后检查其是否有效。

Of course I would like the Age to be equal to 12. This is a toy example, but I am trying to understand how I can have an initialize method that potentially can do all sort of other initialisations and then check that it is valid.

推荐答案

?initialize 帮助页面上的示例中,您需要实际初始化其他对象明智的是,所有插槽都不会被填充。否则,那些 ... 只会吞噬参数,而不会对它们做任何事情。您可以使用 callNextMethod

From the example on the ?initialize help page, you need to actually initialize the object otherwise none of the slots will be filled. Otherwise those ... are just gobbling up the parameters and not doing anything with them. You can invoke the default initialize with callNextMethod

setMethod("initialize", "Person", function(.Object, ...) {
    .Object <- callNextMethod()
    validObject(.Object)
    .Object
})

这篇关于S4构造函数初始化和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆