代码之家  ›  专栏  ›  技术社区  ›  iod

新类的方法如何引用它所替换的基本函数?

  •  1
  • iod  · 技术社区  · 7 年前

    假设我想为我创建的类创建一个方法,但我没有访问原始函数的代码的权限——我只想在它的基础上进行构建。举一个简单的例子,实际上什么都不做:

    x1<-1
    class(x1)<-c("myclass",class(x1))
    print.myclass<-function(x) {
                                x<-paste0(x,"foobar")
                                print(x)
                               }
    print(x1)
    

    x 在将其传递给原始函数之前:

    print.myclass<-function(x) {x<-paste0(x,"foobar"); class(x)<-class(x)[-1]; print(x)}
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Christoph    7 年前

    我认为您的问题在于您创建了一个无限循环: print(print(...) .
    我不知道你想要实现什么,但这可能是你想要的:

    x1 <- 1
    class(x1) <- c("myclass",class(x1))
    print.myclass <- function(x) print.default(x)
    print(x1)
    

    也许你想看看 here

    顺便说一句:我认为你的解决方案并不能真正解决问题。您只需删除导致 print 不使用 print.myclass

    详情请参阅 Hadley

    推荐文章