【问题标题】:R Reference Class multiple inheritance: how to call method in a specific parent class?R Reference Class 多重继承:如何调用特定父类中的方法?
【发布时间】:2015-02-06 14:10:02
【问题描述】:

我有一个引用类Child,它继承自父母SuperASuperB。在Childinitialize方法中,我想依次调用SuperASuperBinitialize方法。

因此,例如,我有:

SuperA <- setRefClass("SuperA",
    fields = list(a = "ANY"),
    methods = list(
        initialize = function(a) {
            print(a)
            initFields(a = a)
        }
    )
)

SuperB <- setRefClass("SuperB",
    fields = list(b = "ANY"),
    methods = list(
        initialize = function(b) {
            print(b)
            initFields(b = b)
        }
    )
)

Child <- setRefClass("Child",
    contains = c("SuperA", "SuperB"),
    methods = list(
        initialize = function(a, b) {
            # attempt to invoke parent constructors one by one:
            SuperA$callSuper(a)
            SuperB$callSuper(b)
        }
    )
)

Child(1, 2)   # want values 1 and 2 to be printed during construction of superclasses

但我得到的只是:

Error in print(a) : argument "a" is missing, with no default 

那么有人对如何调用属于特定父级的方法有任何想法吗?

【问题讨论】:

    标签: r oop inheritance multiple-inheritance reference-class


    【解决方案1】:

    我不是一个重度引用类用户,但在 S4(引用类所基于的)中,最好的方法通常是避免定义初始化方法(这些方法有一个复杂的合同,包括“初始化”和“复制”命名和未命名参数),将setClass() 返回的构造函数视为仅供内部使用,并提供面向用户的构造函数。因此

    .SuperA <- setRefClass("SuperA", fields = list(a = "ANY"))
    
    .SuperB <- setRefClass("SuperB", fields = list(b = "ANY"))
    
    .Child <- setRefClass("Child", contains = c("SuperA", "SuperB"))
    
    Child <- function(a, b)
        ## any coercion, then...
        .Child(a=a, b=b)
    

    结果是

    > Child(a=1, b=2)
    Reference class object of class "Child"
    Field "b":
    [1] 2
    Field "a":
    [1] 1
    

    ?ReferenceClasses 开始,$export(Class) 方法将对象强制转换为 'Class' 的实例,所以

    .SuperA <- setRefClass("SuperA", fields = list(a = "ANY"),
        methods=list(foo=function() .self$a))
    
    .SuperB <- setRefClass("SuperB", fields = list(b = "ANY"),
        methods=list(foo=function() .self$b))
    
    .Child <- setRefClass("Child", contains = c("SuperA", "SuperB"),
        methods=list(foo=function() {
            c(export("SuperA")$foo(), export("SuperB")$foo())
        }))
    
    Child <- function(a, b)
        .Child(a=a, b=b)
    

    导致

    > Child(a=1, b=2)$foo()
    [1] 1 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2019-10-01
      相关资源
      最近更新 更多