S4 构造函数和原型
浏览 Hadley Wickham 的 S4 wiki: https://github.com/hadley/devtools/wiki/S4
setClass("Person", representation(name = "character", age = "numeric"),
prototype(name = NA_character_, age = NA_real_))
hadley <- new("Person", name = "Hadley")
我们如何设计Person 的构造函数(像这样)
Person<-function(name=NA,age=NA){
new("Person",name=name,age=age)
}
不执行此操作:
> Person()
Error in validObject(.Object) :
invalid class "Person" object: 1: invalid object for slot "name" in class "Person": got class "logical", should be or extend class "character"
invalid class "Person" object: 2: invalid object for slot "age" in class "Person": got class "logical", should be or extend class "numeric"
Looking through Hadley Wickham's S4 wiki:
https://github.com/hadley/devtools/wiki/S4
setClass("Person", representation(name = "character", age = "numeric"),
prototype(name = NA_character_, age = NA_real_))
hadley <- new("Person", name = "Hadley")
How can we design a constructor for Person (like this)
Person<-function(name=NA,age=NA){
new("Person",name=name,age=age)
}
that doesn't do this:
> Person()
Error in validObject(.Object) :
invalid class "Person" object: 1: invalid object for slot "name" in class "Person": got class "logical", should be or extend class "character"
invalid class "Person" object: 2: invalid object for slot "age" in class "Person": got class "logical", should be or extend class "numeric"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来答案就在您的示例中:
yield
但是,这相当不符合 S4,并且重复了类定义中已分配的默认值。也许您更愿意
牺牲不带命名参数的调用能力?
It looks like the answer is right there in your example:
yields
However, that is fairly un-S4 and duplicates the default values already assigned in the class definition. Maybe you'd prefer to do
and sacrifice the ability to call without named arguments?
我更愿意为最终用户提供一些有关参数类型的提示,而不是建议使用 @themel 的
...
。还放弃原型并使用length(x@name) == 0
作为字段未初始化的指示,使用People
类而不是Person
,反映了 R 的向量化结构,并在构造函数中使用...
,因此派生类也可以使用构造函数。和
I'd prefer giving the end-user some hints about argument types than the suggestion to use
...
by @themel. Also forgoing the prototype and usinglength(x@name) == 0
as an indication that the field is un-initialized, using aPeople
class rather thanPerson
, reflecting the vectorized structure of R, and using...
in the constructor so derived classes can also use the constructor.And