S3和S4似乎是面向对象编程的官方(即内置)方法。我已经开始使用S3与嵌入在构造函数/方法中的函数的组合。我的目标是有一个对象$ method()类型的语法,以便我有半私人领域。我说半私密,因为没有办法真正隐藏它们(据我所知)。下面是一个简单的例子,实际上并没有做任何事情:
#' Constructor
EmailClass <- function(name, email) {
nc = list(
name = name,
email = email,
get = function(x) nc[[x]],
set = function(x, value) nc[[x]] <<- value,
props = list(),
history = list(),
getHistory = function() return(nc$history),
getNumMessagesSent = function() return(length(nc$history))
)
#Add a few more methods
nc$sendMail = function(to) {
cat(paste("Sending mail to", to, 'from', nc$email))
h <- nc$history
h[[(length(h)+1)]] <- list(to=to, timestamp=Sys.time())
assign('history', h, envir=nc)
}
nc$addProp = function(name, value) {
p <- nc$props
p[[name]] <- value
assign('props', p, envir=nc)
}
nc <- list2env(nc)
class(nc) <- "EmailClass"
return(nc)
}
#' Define S3 generic method for the print function.
print.EmailClass <- function(x) {
if(class(x) != "EmailClass") stop();
cat(paste(x$get("name"), "'s email address is ", x$get("email"), sep=''))
}
和一些测试代码:
test <- EmailClass(name="Jason", "[email protected]")
test$addProp('hello', 'world')
test$props
test
class(test)
str(test)
test$get("name")
test$get("email")
test$set("name", "Heather")
test$get("name")
test
test$sendMail("[email protected]")
test$getHistory()
test$sendMail("[email protected]")
test$getNumMessagesSent()
test2 <- EmailClass("Nobody", "[email protected]")
test2
test2$props
test2$getHistory()
test2$sendMail('[email protected]')
这里是一个博客帖子我写的这个做法的链接:http://bryer.org/2012/object-oriented-programming-in-r我欢迎评论,批评和建议,因为如果这是最好的方法,我不相信自己。但是,对于我试图解决的问题,它效果很好。特别是,对于makeR软件包(http://jbryer.github.com/makeR),我不希望用户直接更改数据字段,因为我需要确保表示对象状态的XML文件保持同步。只要用户遵守我在文档中概述的规则,就可以很好地工作。
参考资料上的信息:http://stackoverflow.com/questions/5137199/what-is-the-significance-of-the-new-reference-classes – 2012-03-01 18:29:07
谢谢,你能重新发布链接作为答案吗?如果你可以包含什么参考类的小概要,以及为什么他们更喜欢S3/S4类,那将会很好。 – 2012-03-01 18:34:19
一只小鸟在我耳边低声说约翰钱伯斯即将出版一本书。但不要告诉任何人我说过的话; ;-) – 2012-03-01 18:41:53