R(S3)面向对象编程,以泛型函数方式实现。
1. 创建对象
library(pryr)
1)通过变量创建S3对象
x <- 1
attr(x,'class') <- 'foo'
class(x)
otype(x)
2)通过structure()函数创建S3对象
y <- structure(2, class = "foo")
3)创建一个多类型的S3对象
x <- 1
attr(x,'class')<- c("foo", "bar")
2. 创建泛型函数
teacher <- function(x) UseMethod("teacher")
teacher.lecture <- function(x) print("讲课")
teacher.correcting <- function(x) print("批改作业")
teacher.default<-function(x) print("你不是teacher")
3. 使用泛型函数
1) 间接调用
a<-'teacher'
attr(a,'class') <- 'lecture'
teacher(a)
2) 直接调用
t
eacher.lecture()
评论