使用类创建列表
本课属于 Coddy R 学习旅程的“面向对象编程”单元。第 2 课,共 57 课。
S3 是 R 最早出现、使用最广泛的对象系统。S3 对象是一个普通列表,带有 class 属性,用来标明它属于哪种对象。class(x) <- "dog" 用于设置这个标记:
rex <- list(name = "Rex", age = 3)
class(rex) <- "dog"
print(class(rex))
cat(rex$name, "is", rex$age)输出:
[1] "dog"
Rex is 3structure() 会在一次调用中构建值并设置其属性,这是创建 S3 对象的常用方式。和读取任何列表一样,可以用 $ 读取各个字段:
rex <- structure(list(name = "Rex", age = 3), class = "dog")
print(class(rex))
print(is.list(rex))
print(rex$age)输出:
[1] "dog"
[1] TRUE
[1] 3类只是一个标签:R 不会检查对象包含哪些字段,因此任何列表都可以称为 dog。unclass() 会移除标签,并返回普通列表:
p <- structure(list(x = 1, y = 2), class = "point")
print(unclass(p))输出:
$x
[1] 1
$y
[1] 2S3 对象是值。改变对象的函数改变的是它自己的副本,因此会返回新版本,并由调用者将其赋给变量。原对象保持不变:
birthday <- function(d) {
d$age <- d$age + 1
d
}
rex <- structure(list(name = "Rex", age = 3), class = "dog")
older <- birthday(rex)
cat(rex$age, older$age)输出:
3 4挑战
简单完成 make_pet(name, species, age) 函数,在 Pet.R 中定义。它会按顺序返回一个包含 name、species 和 age 字段的列表,并设置类为 pet。然后完成 describe_pet(p) 函数,它会返回一个句子:宠物名为 Rex、物种为 dog、年龄为 3 时,返回 Rex is a 3 year old dog。
提供的代码会读取名称、物种和年龄,创建宠物,并输出它的类、字段名称和句子。
你的代码写在 Pet.R 中。main.R 包含提供的输入输出代码,不能编辑。
亲手试试
source("Pet.R")
# 提供的输入输出代码:保持原样。
input <- suppressWarnings(readLines(file("stdin")))
p <- make_pet(input[1], input[2], as.numeric(input[3]))
cat("class: ", class(p), "\n", sep = "")
cat("fields: ", paste(names(p), collapse = ", "), "\n", sep = "")
cat(describe_pet(p), "\n", sep = "")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: R 在线编译器