【问题标题】:Changing cloning behavior in R6 classes更改 R6 类中的克隆行为
【发布时间】:2018-12-26 18:19:22
【问题描述】:

假设我有一个 R6 类,其中一个元素是指向某个 C++ 对象的外部指针。

所以我有这样的事情:

myClass <- R6::R6Class(
  "myClass", 
  public = list(
    xp = NULL,
    initialize = function(x) {
      self$xp = cpp_fun_that_returns_a_pointer(x)
    }
  )
)

如果我使用myclass$clone(),它仍然会指向相同的myclass$xp。如果我这样做myclass$clone(deep = TRUE) 也会发生这种情况,因为它不知道如何在 C++ 端进行克隆。

在这种情况下,我可以使用自定义的deep_clone 方法...

但由于在我的用例中,如果没有深度克隆克隆类总是错误的,我想知道是否可以直接更改clone 的行为。

我尝试创建一个 clone() 方法,但 R6 不允许这样做。

Error in R6::R6Class("tensor", cloneable = FALSE, private = list(xp = NULL),  : 
  Cannot add a member with reserved name 'clone'.

【问题讨论】:

  • 当然。你可以把它改成你想要的。您可以使用myClass$clone_method查看当前代码并使用myClass$clone_method &lt;- NewCode分配新代码
  • 不确定它是否有效。 clone 似乎没有在课堂上调用任何 clone_method。

标签: r r6


【解决方案1】:

如果您使用cloneable = FALSE,您可以定义自定义clone() 方法。我不确定你在用XPtrs 做什么,所以我将演示一个稍微简单的示例:

# Set up the R6 class, making sure to set cloneable to FALSE
myClass <- R6::R6Class(
    "myClass", 
    public = list(
        xp = NULL,
        initialize = function(x = 1:3) {
            self$xp = x
        }
    ),
    cloneable = FALSE
)
# Set the clone method
myClass$set("public", "clone", function() {
    print("This is a custom clone method!") # Test print statement
    myClass$new(self$xp)
})
# Make a new myClass object
a <- myClass$new(x = 4:6)
# Examine it
a
#> <myClass>
#>   Public:
#>     clone: function () 
#>     initialize: function (x = 1:3) 
#>     xp: 4 5 6
# Clone it
b <- a$clone()
#> [1] "This is a custom clone method!"
# We see the test print statement was printed!
# Let's check out b:
b
#> <myClass>
#>   Public:
#>     clone: function () 
#>     initialize: function (x = 1:3) 
#>     xp: 4 5 6

由reprex package (v0.2.1) 于 2019 年 2 月 5 日创建

【讨论】:

  • 谢谢!这正是我所需要的。将尽可能奖励赏金。
  • @DanielFalbel 很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
相关资源
最近更新 更多