【问题标题】:Reference class inheritance from external package从外部包引用类继承
【发布时间】:2023-03-17 13:50:01
【问题描述】:

我正在尝试覆盖引用类方法。因为引用类方法绑定到类而不是对象,我相信为了做到这一点,我需要定义一个继承自旧引用类的新引用类。然而,我试图继承的类是在我的外部包(dplyr)中定义的。我无法弄清楚执行此操作的正确语法,包含似乎只需要一个文本名称,并且不搜索外部包中的类定义。

特别是我试图从 dplyr 继承 DbDisconnector 引用类并覆盖 finalize 方法。

这会正确地找到父类,但不能分配给它,因为它来自不同的包。

NewDbDisconnector <- setRefClass("NewDbDisconnector",
  contains = 'DbDisconnector',
  methods = list(
    finalize = function() {
      message("test")
    }
  ),
  where=getNamespace('dplyr')
)
# Error in assign(mname, def, where) (from file.r#75) :
#  cannot add bindings to a locked environment

包含的方法只接受字符串,不能只从 getRefClass 获得 refClass 定义。

NewDbDisconnector <- setRefClass("NewDbDisconnector",
  contains = getRefClass("DbDisconnector", getNamespace("dplyr")),
  methods = list(
    finalize = function() {
      message("test")
    }
  )
)
# Error in FUN(X[[1L]], ...) :
#  the 'contains' argument should be the names of superclasses:  got an element of class “name”

我认为这应该是可能的,我只是想不出正确的方法。

【问题讨论】:

  • 见discussion。我认为这可能是引用类的限制。
  • 我认为这是不可能的,因为引用类的方式。对于这个特定的课程,我认为它很简单,您可以拥有自己的内部副本。
  • 谢谢大家,这很不幸。正如@hadley 所说的那样,这个类很简单,我可以复制它。

标签: r dplyr reference-class


【解决方案1】:

您可以将超类导入您的环境:

DbDisconnector <- getFromNamespace("DbDisconnector", "dplyr")

然后在你的类中设置contains = "DbDisconnector"。

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多