【发布时间】:2020-11-30 17:07:54
【问题描述】:
我正在阅读Advanced R by Hadley Wickham,但我对13.7.3 Group Generics部分感到困惑。
我对措辞有点困惑,“......你不能定义你自己的组泛型......为你的班级定义一个单一的组泛型......”但我认为本节的意思是说,如果我定义通用组Math.MyClass 然后Math 组通用(abs、sign 等)中的所有函数将被MyClass 对象覆盖。
这可以通过运行以下命令来确认:
my_class <- structure(.Data = -1, class = "MyClass")
my_class
# [1] -1
# attr(,"class")
# [1] "MyClass"
abs(my_class)
# [1] 1
# attr(,"class")
# [1] "MyClass"
Math.MyClass <- function(x) { x }
abs(my_class)
# [1] -1
# attr(,"class")
# [1] "MyClass"
我知道这遵循special naming scheme generic.class 但为什么.Data 的值会在abs(my_class) 中受到影响?
当我创建变量my_class时,我设置了参数.Data = -1,而-1的类是numeric,这不应该改变:
class(unclass(my_class))
# [1] "numeric"
my_numeric <- unclass(my_class)
class(my_numeric)
# [1] "numeric"
abs(my_numeric)
# [1] 1
那么为什么abs(my_class) 在我定义Math.MyClass 之前和之后不打印相同的结果(1)?
如果我将泛型组定义为Math.MyClass <- function(x) {NextMethod()},我在定义Math.MyClass 之前和之后确实会收到相同的结果,但是那么拥有组泛型有什么意义呢?
而且,当我运行以下命令时,为什么我在定义 Math.matrix 之前和之后都会得到相同的 abs(my_matrix) 答案:
my_matrix <- matrix(data = -1:-10, ncol = 5) + 0.0
class(my_matrix)
# [1] "matrix"
class(my_matrix[1,1])
# [1] "numeric"
my_matrix
# [,1] [,2] [,3] [,4] [,5]
# [1,] -1 -3 -5 -7 -9
# [2,] -2 -4 -6 -8 -10
abs(my_matrix)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 3 5 7 9
# [2,] 2 4 6 8 10
Math.matrix <- function(x) { x }
abs(my_matrix)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 3 5 7 9
# [2,] 2 4 6 8 10
当我运行以下命令时:
your_class <- structure(.Data = list(-1), class = "YourClass")
your_class
# [[1]]
# [1] -1
#
# attr(,"class")
# [1] "YourClass"
abs(your_class)
# Error in abs(your_class) : non-numeric argument to mathematical function
class(unclass(your_class))
# [1] "list"
your_list <- list(-1)
class(your_list)
# [1] "list"
abs(your_list)
# Error in abs(your_list) : non-numeric argument to mathematical function
很明显,.Data 的 class 确实很重要(最初无论如何),因为 abs(your_class) 和 abs(your_list) 都会导致相同的错误。
为了让事情变得更具挑战性,我发现运行 rm(Math.MyClass) 后,MyClass 对象的一切都恢复正常了:
my_class
# [1] -1
# attr(,"class")
# [1] "MyClass"
abs(my_class)
# [1] -1
# attr(,"class")
# [1] "MyClass"
rm(Math.MyClass)
abs(my_class)
# [1] 1
# attr(,"class")
# [1] "MyClass"
有人可以更完整地解释什么是组泛型(为什么存在组泛型/它们完成什么/它们与 R 对象的父子关系是什么/为什么当组泛型时某些对象中的data 参数会受到影响?已定义而其他未定义 /etc)?
如果您觉得用 Python 示例解释起来更容易,我在 Python 中的 OOP 方面比在 R 中更有经验。非常感谢任何帮助!
【问题讨论】: