类槽与初始化签名不匹配 [英] Class slots vs. initialize signature mismatch

查看:67
本文介绍了类槽与初始化签名不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 S4 课程:

Consider the following S4 class:

setClass('Foo', representation(model='data.frame'))

setMethod('initialize', 'Foo',
      function(.Object, a, b) {
        .Object@model <- data.frame(a, b)
        .Object
      })

它可以实例化:

new('Foo', a=1:4, b=4:7)

到目前为止一切顺利.但是,当我尝试对 Foo 进行子类化时,出现错误.

So far so good. However, when I try to subclass Foo I get an error.

setClass('Bar', contains='Foo')
>>> Error in data.frame(a, b) : argument "a" is missing, with no default

就我个人而言,我更喜欢使用显式参数实例化 Foo 类,因为代码更......好吧,显式.然而,这似乎不可能,不是吗?看起来 initialize 的签名必须与类拥有的插槽匹配,否则就是等待发生的问题.我错了吗?

Personally, I would prefer to instantiate class Foo with explicit arguments because the code is more... well, explicit. However, this does not seem possible, does it? It looks like the signature of initialize must match the slots that the class has, otherwise it's a problem waiting to happen. Am I wrong?

推荐答案

要求是 new 不带参数调用,new("Foo") 必须工作.此外,您的初始化方法可能更好的做法是采用 ...callNextMethod,并在 之后 使用参数... (因为 initialize 被记录为使用未命名的参数来初始化包含的类).所以

The requirement is that new called with no arguments, new("Foo"), must work. Also, it's probably better practice for your initialize method to take ..., to callNextMethod, and to have arguments after the ... (because initialize is documented to use unnamed arguments for initializing contained classes). So

setMethod(initialize, "Foo", function(.Object, ..., a=integer(), b=integer()) {
    callNextMethod(.Object, ..., model=data.frame(a, b))
})

通常希望将用户与调用 new 隔离开来,而是使用构造函数 Foo.通常,构造函数会执行您可能在 initialize 方法中进行的任何强制转换,因此只是未指定 initialize 方法.

Normally one wants to insulate the user from calling new, and will instead use a constructor Foo. Typically the constructor does whatever coercion you might have instead put in the initialize method, so the initialize method is just not specified.

Foo <- function(a=integer(), b=integer(), ...) {
    model <- data.frame(a, b)
    new("Foo", model=model, ...)
}

这篇关于类槽与初始化签名不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆