【问题标题】:How can I overwrite the to string method of an R6Class in R language?如何用 R 语言覆盖 R6Class 的 to string 方法?
【发布时间】:2021-09-21 17:09:30
【问题描述】:

我已经尝试将 to_string() 函数添加到类的公共部分,但我正在寻找一种方法,例如 C# 中的覆盖。

【问题讨论】:

    标签: r class tostring r6


    【解决方案1】:

    toString() 是一个 S3 泛型,因此可以使用 toString.{className} 为您的类定义它

    MyClass <- R6::R6Class(
      "MyClass",
      list(i = 0)
    )
    
    toString.MyClass <- function(x, ...) {
      paste("i is", x$i)
    }
    
    my_object <- MyClass$new()
    toString(my_object)
    #> [1] "i is 0"
    my_object$i <- 1
    toString(my_object)
    #> [1] "i is 1"
    

    通过查看源代码,您可以看到它是 S3 泛型

    toString
    #> function (x, ...) 
    #> UseMethod("toString")
    #> <bytecode: 0x55fb2afe7d68>
    #> <environment: namespace:base>
    

    UseMethod 表示它将根据第一个参数的类(x)转发调用,如果没有给出特定类的toString 实现,则将调用toString.default()

    【讨论】:

      猜你喜欢
      • 2022-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 2021-12-29
      相关资源
      最近更新 更多