参考类的有效性方法 [英] Validity Method for Reference Classes

查看:42
本文介绍了参考类的有效性方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 S4 中,我可能会这样做:

In S4 I might do something like this:

setClass(
  "test", slots=c(a="integer"), 
   validity=function(object) if(length(object@a) != 1L) "not scalar" else TRUE
)

引用类的等价物是什么?我在引用类的上下文中找不到任何对有效性函数的引用.我必须依赖定义 setter 类吗?虽然基于参考类文档中的此评论:

What is the equivalent for reference classes? I could not find any references to validity functions in the context of reference classes. Must I rely on defining setter classes? Though based on this comment in the reference class docs:

许多使用 OOP 编程范式的系统推荐或强制执行对应于每个字段的 getter 和 setter 方法,而不是按名称直接访问.如果您喜欢这种风格,并希望通过 x$getAbc() 提取名为 abc 的字段并通过 x$setAbc(value) 为其赋值,则 $accessors 方法是一个为指定字段创建此类 getter 和 setter 方法的便捷函数.否则就没有理由使用这种机制.

A number of systems using the OOP programming paradigm recommend or enforce getter and setter methods corresponding to each field, rather than direct access by name. If you like this style and want to extract a field named abc by x$getAbc() and assign it by x$setAbc(value), the $accessors method is a convenience function that creates such getter and setter methods for the specified fields. Otherwise there is no reason to use this mechanism.

似乎应该有另一种方式.

it would seem there should be another way.

推荐答案

可以在引用类上设置有效性方法

It's possible to set a validity method on the reference class

.A <- setRefClass("A", fields=list(x="numeric"))

setValidity("A", function(object) {
    if (length(object$x) != 1)
        "'x' must be length 1"
    else TRUE
})

但并非在所有可能有用的情况下都会调用它

but it's not invoked under all circumstances where it might be useful

> .A()
Reference class object of class "A"
Field "x":
numeric(0)
> .A(x=1:5)
Reference class object of class "A"
Field "x":
[1] 1 2 3 4 5
> validObject(.A(x=1:5))
Error in validObject(.A(x = 1:5)) : 
  invalid class "A" object: 'x' must be length 1

在某些方面,这与 S4 没有什么不同/不那么古怪

In some ways this is no different / less quirky than S4

.B <- setClass("B", representation(x="numeric"))

setValidity("B", function(object) {
    if (length(object@x) != 1)
        "'x' must be length 1"
    else TRUE
})

> .B()                 # no validity checking!
An object of class "B"
Slot "x":
numeric(0)

> validObject(.B())
Error in validObject(.B()) : 
  invalid class "B" object: 'x' must be length 1
> .B(x=1:5)
Error in validObject(.Object) : 
  invalid class "B" object: 'x' must be length 1
> b = .B(x=1L)
> b@x <- 1:5          # no validity checking@!
> validObject(b)
Error in validObject(b) : invalid class "B" object: 'x' must be length 1

这篇关于参考类的有效性方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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