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(obj$name, "\n")
cat(obj$age, "\n")
cat(obj$rno, "\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(obj$name, "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")
输出:
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
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)
输出:
Utkarsh
21
96
引用类中的继承
引用类中的继承与 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")
s$dec_age(5)
s$age
cat("Decrease age by 20\n")
s$dec_age(20)
s$age
输出:
[1] 16
Error in s$dec_age(20) : Age cannot be negative
[1] 16