全部版块 我的主页
论坛 休闲区 十二区 灌水吧
971 0
2017-01-01
R的面向对象编程
R的面向对象编程是基于泛型函数(generic function)的,而不是基于类层次结构。接下来,我从面向对象的3个特征入手,分别用R语言进行实现,使用的案例为上文中,老师和学生的3幅图。
1 R语言实现封装
# 定义老师对象和行为
> teacher <- function(x, ...) UseMethod("teacher")
> teacher.lecture <- function(x) print("讲课")
> teacher.assignment <- function(x) print("布置作业")
> teacher.correcting <- function(x) print("批改作业")
> teacher.default<-function(x) print("你不是teacher")
# 定义同学对象和行为
> student <- function(x, ...) UseMethod("student")
> student.attend <- function(x) print("听课")
> student.homework <- function(x) print("写作业")
> student.exam <- function(x) print("考试")
> student.default<-function(x) print("你不是student")
# 定义两个变量,a老师和b同学
> a<-'teacher'
> b<-'student'
# 给老师变量设置行为
> attr(a,'class') <- 'lecture'
# 执行老师的行为
> teacher(a)
[1] "讲课"
# 给同学变量设置行为
> attr(b,'class') <- 'attend'
# 执行同学的行为
> student(b)
[1] "听课"
> attr(a,'class') <- 'assignment'
> teacher(a)
[1] "布置作业"
> attr(b,'class') <- 'homework'
> student(b)
[1] "写作业"
> attr(a,'class') <- 'correcting'
> teacher(a)
[1] "批改作业"
> attr(b,'class') <- 'exam'
> student(b)
[1] "考试"
# 定义一个变量,既是老师又是同学
> ab<-'student_teacher'
# 分别设置不同对象的行为
> attr(ab,'class') <- c('lecture','homework')
# 执行老师的行为
> teacher(ab)
[1] "讲课"
# 执行同学的行为
> student(ab)
[1] "写作业"


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群