【发布时间】:2014-01-20 20:19:00
【问题描述】:
我是 R 中面向对象编程的新手,并且不知道如何正确编写修改对象的函数。
这个例子有效:
store1 <- list(
apples=3,
pears=4,
fruits=7
)
class(store1) <- "fruitstore"
print.fruitstore <- function(x) {
paste(x$apples, "apples and", x$pears, "pears", sep=" ")
}
print(store1)
addApples <- function(x, i) {
x$apples <- x$apples + i
x$fruits <- x$apples + x$pears
return(x)
}
store1 <- addApples(store1, 5)
print(store1)
但我认为应该有一种更简洁的方法来做到这一点,而无需返回整个对象:
addApples(store1, 5) # Preferable line...
store1 <- addApples(store1, 5) # ...instead of this line
在 R 中编写修改函数的正确方法是什么? “
更新:感谢大家为 R 中的 OOP 带来的 Rosetta Stone。非常有用。 我试图解决的问题在流程方面非常复杂,因此参考类的刚性可能会带来结构的帮助。我希望我能接受所有回复作为答案,而不仅仅是一个。
【问题讨论】:
-
如果你真的想就地修改,那么也许你不应该使用 S3 对象,而是使用reference class 对象。
-
好评论。引用类的目的突然变得有意义了。