可以从类内部获取R6类名吗?

huangapple go评论99阅读模式
英文:

Can we get R6 class name from inside the class?

问题

需要从类内部获取R6类变量的名称。可以这样做吗?就像下面的示例一样:

Simple <- R6Class("Simple",
                  public = list(
                    myname = NA,
                    dt = NA, 
                    initialize = function () {
                      self$myname = substitute(self)
                    }
                  )              
)
mysimple <- Simple$new()  
mysimple$myname 

这将返回self
我希望这返回mysimple

这对于使用saveRDS()存储类变量,然后使用saveRDS()进行恢复将非常有用。

英文:

I need to get the name of the R6 class variable from inside the class.
Can I do that? - like in example below:

  Simple &lt;- R6Class(  &quot;Simple&quot;,
                      public = list(
                        myname = NA,
                        dt = NA, 
                        initialize = function () {
                          self$myname = substitute(self)
                        }
                      )              
  )
  mysimple &lt;- Simple$new()  
  mysimple$myname 

This returns self.
And i want this to return mysimple.

This would be useful for storing a class variable with saveRDS() and then restoring it with saveRDS()

答案1

得分: 1

是的,你可以使用 class(self)[1],例如:

Simple <- R6Class(
  "Simple",
  public = list(
    getClass = function(){
      class(self)[1]
    }
  )
)

mysimple <- Simple$new()

mysimple$getClass()

基于GitHub问题中的解决方案:https://github.com/r-lib/R6/issues/135

英文:

Yes, you can use class(self)[1] e.g.

Simple &lt;- R6Class(
  &quot;Simple&quot;,
  public = list(
    getClass = function(){
      class(self)[1]
    }
  )
)

mysimple &lt;- Simple$new()

mysimple$getClass()

Based on the solution in the GitHub issues: https://github.com/r-lib/R6/issues/135

huangapple
  • 本文由 发表于 2023年3月4日 08:31:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定