R语言 继承
继承 是面向对象编程中的一个概念,通过它,新的类可以从现有的或基类中派生出来,有助于代码的重复使用。派生类可以与基类相同,也可以有扩展的功能,这就在编程环境中形成了类的分层结构。在这篇文章中,我们将讨论在R编程中如何通过三种不同类型的类来进行继承。
S3类的继承
R编程语言中的S3类没有正式和固定的定义。在S3对象中,一个带有类属性的列表被设置为一个类名。S3类对象只继承其基类的方法。
例子
# Create a function to create an object of class
student <- function(n, a, r){
value <- list(name = n, age = a, rno = r)
attr(value, "class") <- student
value
}
# Method for generic function print()
print.student <- function(obj){
cat(objname, "\n")
cat(objage, "\n")
cat(objrno, "\n")
}
# Create an object which inherits class student
s <- list(name = "Utkarsh", age = 21, rno = 96,
country = "India")
# Derive from class student
class(s) <- c("InternationalStudent", "student")
cat("The method print.student() is inherited:\n")
print(s)
# Overwriting the print method
print.InternationalStudent <- function(obj){
cat(objname, "is from", obj$country, "\n")
}
cat("After overwriting method print.student():\n")
print(s)
# Check imheritance
cat("Does object 's' is inherited by class 'student' ?\n")
inherits(s, "student")
R
输出
The method print.student() is inherited:
Utkarsh
21
96
After overwriting method print.student():
Utkarsh is from India
Does object 's' is inherited by class 'student' ?
[1] TRUE
R
S4类的继承性
R编程中的S4类有适当的定义,派生类能够继承其基类的属性和方法。
例子
# Define S4 class
setClass("student",
slots = list(name = "character",
age = "numeric", rno = "numeric")
)
# Defining a function to display object details
setMethod("show", "student",
function(obj){
cat(obj@name, "\n")
cat(obj@age, "\n")
cat(obj@rno, "\n")
}
)
# Inherit from student
setClass("InternationalStudent",
slots = list(country = "character"),
contains = "student"
)
# Rest of the attributes will be inherited from student
s <- new("InternationalStudent", name = "Utkarsh",
age = 21, rno = 96, country="India")
show(s)
R
输出
Utkarsh
21
96
R
参考类中的继承
引用类中的继承与S4类几乎相似,使用setRefClass()函数来执行继承。
例子
# Define class
student <- setRefClass("student",
fields = list(name = "character",
age = "numeric", rno = "numeric"),
methods = list(
inc_age <- function(x) {
age <<- age + x
},
dec_age <- function(x) {
age <<- age - x
}
)
)
# Inheriting from Reference class
InternStudent <- setRefClass("InternStudent",
fields = list(country = "character"),
contains = "student",
methods = list(
dec_age <- function(x) {
if((age - x) < 0) stop("Age cannot be negative")
age <<- age - x
}
)
)
# Create object
s <- InternStudent(name = "Utkarsh",
age = 21, rno = 96, country = "India")
cat("Decrease age by 5\n")
sdec_age(5)
sage
cat("Decrease age by 20\n")
sdec_age(20)
sage
R
输出
[1] 16
Error in s$dec_age(20) : Age cannot be negative
[1] 16
R