有没有办法使用它自己的方法删除 R6 对象?

Is there any way to remove an R6 object using it's own method?

以下面给出的基本 R6 class 为例:

library(R6)

Demo = R6Class("Demo",
           public = list(
             initialize = function(){
               message("demo object initialized!")
             },
             delete = function(){
               #should contain the logic to delete the object
               gc()
             },
             finalize = function(){
               message("demo object deleted!")
             } 
           ))

demoObj = Demo$new()
demoObj$delete()

删除函数内部的逻辑应该是什么?是否可以删除对象(self)?

我不知道有任何直接的方法可以通过这种方式将 R 中的对象转换为“self-destruct”。对象属于创建它的环境,有充分的理由将对象生命周期的控制权交给创建它的环境,而不是对象本身。

这并不意味着没有办法做到这一点,但实际上您必须允许对象在其父框架中查找自己的名称(使用仅在删除过程完成后才标识它的标志)启动),然后在父框架中对该名称调用 rm。所以像这样的代表:

library(R6)

Demo = R6Class("Demo",
           public = list(
             initialize = function(){
               message("demo object initialized!")
             },
             delete_flag = FALSE,
             delete = function(){
               self$delete_flag <- TRUE
               pf <- parent.frame()
               demos <- sapply(ls(pf), function(i) {
                          class(get(i, envir = pf))[1] == "Demo"
                        })
               this <- ls(pf)[demos][sapply(mget(ls(pf)[demos], envir = pf),
                      function(x) x$delete_flag)]
               rm(list = this, envir = pf)
               message("demo object deleted!")
             }
           ))

demoObj = Demo$new()
#> demo object initialized!

ls()
#> [1] "Demo"    "demoObj"

demoObj$delete()
#> demo object deleted!

ls()
#> [1] "Demo"

这是为了确保只删除正确的对象,例如;

demoObj1 = Demo$new()
#> demo object initialized!
demoObj2 = Demo$new()
#> demo object initialized!
demoObj3 = Demo$new()
#> demo object initialized!

demoObj2$delete()
#> demo object deleted!

ls()
#> [1] "Demo"     "demoObj1" "demoObj3"

可以看到只有demoObj2删除了自己

reprex package (v0.3.0)

于 2020-08-08 创建