在 R 中为多个类定义类函数

问题描述 投票:0回答:1

我有一个类

"model"
并且我已经为这个类定义了一个打印函数

model.print(object){
  print(model$beta)
}

现在假设我有另一个类

"model_2"
,我想为其使用完全相同的打印函数。有没有一种更简单的方法来为此类定义此函数,而无需单独编写完整的
model_2.print
函数?

r
1个回答
0
投票

也许下面的代码可以解决您的问题。

print
类对象的
"model_2"
方法调用
"model"
类对象的方法,不执行任何其他操作,因此结果几乎相同。
区别在于参数的类别。
在第一种情况下,

attr(,"class")
[1] "model" "numeric"

第二种情况

attr(,"class")
[1] "model_2" "numeric"

现在是一个工作示例。

print.model <- function(x, ...) {
  message("This is 'print.model'")
  print.default(x)
}
print.model_2 <- function(x, ...) {
  print.model(x, ...)
}
as_model <- function(x) {
  class(x) <- c("model", class(x))
  x
}
as_model_2 <- function(x) {
  class(x) <- c("model_2", class(x))
  x
}

x <- as_model(1:5)
y <- as_model_2(rnorm(4))

x
#> This is 'print.model'
#> [1] 1 2 3 4 5
#> attr(,"class")
#> [1] "model"   "integer"
y
#> This is 'print.model'
#> [1] -0.1329577 -0.5115048 -3.1441337 -0.3179638
#> attr(,"class")
#> [1] "model_2" "numeric"

创建于 2024-04-26,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.