带类的打印功能

时间:2020-02-18 06:32:22

标签: r

x <- structure(1:3, foo = 42, class = "hello")

x
[1] 1 2 3
attr(,"foo")
[1] 42
attr(,"class")
[1] "hello"

但是如果我们设置

print.hello <- function(x, ...){
    print(123)
}

x将成为

x
[1] 123

为什么print.hello函数会覆盖x中的所有内容?

P.S。我正在阅读使用R的动手编程,10.4.1方法分派

1 个答案:

答案 0 :(得分:2)

不是,x保持不变,但是x的打印内容会发生变化。

> x <- structure(1:3, foo = 42, class = "hello")
> print.hello <- function(x, ...){
>   print("asffdas")
> }
> x
[1] "asffdas"
> as.numeric(x)
[1] 1 2 3
相关问题