更新时间:2023-12-02 20:12:22
R6
是我需要的框架.
# R6 ----------------------------------------------------------------------
student <- R6Class("student", list(
age = 0,
initialize = function(age = 20) {
#stopifnot(is.character(name), length(name) == 1)
stopifnot(is.numeric(age), length(age) == 1)
#self$name <- name
self$age <- age
},
getolder = function(years = 1) {
self$age <- self$age + years
invisible(self)
}
)
)
student$new()
stud1 <- student$new(age = 15)
stud1$getolder(3)
stud1$age #18
stud2 <- student$new(age = 15)
group <- R6Class("group", list(
s1 = NA,
s2 = NA,
initialize = function(s1=NA, s2=NA) {
if(!all(sapply(list(s1, s2), function(x) inherits(x,"student")))) stop("students not students")
self$s1 <- s1
self$s2 <- s2
},
getolder = function(stud, years = 1) {
stud$getolder(years)
invisible(self)
}))
gr1 <- group$new(stud1, stud2)
gr1$s1$age #18
gr1$getolder(gr1$s1, years=10)
gr1$s1$age #28
向 hadley 的 高级 R 书 大喊大叫,它预先指定了 R6 对象.
Shout out to hadley's advanced R book which specified upfront the mutable property of R6
objects.