【问题标题】:Initialize R6 class with an instance of Class and return the same Class用 Class 的实例初始化 R6 类并返回相同的 Class
【发布时间】:2020-07-16 08:45:26
【问题描述】:

给定一个 R6 类 Class1 及其 initialize 函数,我希望能够传递同一类的实例并直接返回它。

类似这样的:

if("Class1" %in% class(x)) x
else Class1$new(x)

但是在 R6 类的 initialize 函数中,它应该像这样工作

# This script does not work
# Definition of the class
Class1 = R6::R6Class("Class1",
                     public=list(
                       initialize = function(x){
                         # This line does not work
                         if("Class1"%in%class(x)) return(x)
                       }
                     ))
# Initiate an instance from scratch
foo = Class1$new()
# Initiate an instance through another instance
bar = Class1$new(foo)
# The two should be the same
identical(foo, bar)
#> TRUE

【问题讨论】:

    标签: r r6


    【解决方案1】:

    在 R6 的当前状态下,这似乎是不可能的。检查原始代码 github.com/r-lib/R6/blob/master/R/new.R 。最重要的是应用初始化的第 154 行和返回 public_bind_env 的第 194 行。问题是,即使使用超级分配,我认为我们也无法覆盖它,因为所有东西都是从具有自己地址的新空环境构建的。 这种使用包装器的解决方案在市场上被广泛使用,它正在做它应该做的事情:

    class1 <- function(x = NULL) {
      
      if(inherits(x, "Class1")) x else Class1$new(x)
        
    }
    
    Class1 = R6::R6Class("Class1",
                         public=list(
                           initialize = function(x = NULL){
                           }
                         ))
    # Initiate an instance from scratch
    foo = class1()
    # Initiate an instance through another instance
    bar = class1(foo)
    # The two should be the same
    identical(foo, bar)
    #> TRUE
    
    

    【讨论】:

    • 谢谢,但这不是我问的。正如问题所述,我希望能够在 initialize 函数中执行此操作。
    • 这可能是不可能的。检查原始代码github.com/r-lib/R6/blob/master/R/new.R。最重要的是第 154 行应用了初始化,第 194 行返回了 public_bind_env。问题是,即使使用超级分配,我认为我们也无法覆盖它,因为所有东西都是从具有自己地址的新空环境构建的。我给了这个解决方案,因为它在市场上被使用,它正在做它应该做的事情。
    • 谢谢。现在,我明白为什么在initialize 函数中添加return 语句不起作用了。您能否在答案中包含您的评论以解释为什么这是唯一的方法?所以我可以将其标记为已接受。
    • 完成。很高兴能提供帮助。
    猜你喜欢
    • 2019-09-16
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多