gpt4 book ai didi

oop - 有没有办法为 S4 引用类声明公共(public)和私有(private)方法?

转载 作者:行者123 更新时间:2023-12-03 11:29:31 26 4
gpt4 key购买 nike

前期:我上午 知道 R 是一种函数式语言,所以请不要咬 ;-)

我有 很棒在我的许多程序中使用 OOP 方法的经验。
现在,我想知道在使用 S4 Reference Classes 时是否有办法区分公共(public)方法和私有(private)方法。在 R?

例子

类定义

setRefClass("B",
field=list(
b.1="numeric",
b.2="logical"
),
methods=list(
thisIsPublic=function(...) {
thisIsPublic_ref(.self=.self, ...)
},
thisIsPrivate=function(...) {
thisIsPrivate_ref(.self=.self, ...)
}
)
)

setRefClass("A",
field=list(
a.1="B"
)
)

注意

我通常不会将实际的方法定义放在类 def 中,而是将其分隔为 S4 方法(即 thisIsPublic_ref ),原因如下:
  • 这样,类 def 保持清晰的排列,并且在单个方法 def 变得非常大的情况下更易于阅读。
  • 它允许您随时切换到方法的功能执行。成为 x某个类的实例,你可以调用foo_ref(.self=x)而不是 x$foo() .
  • 它允许您通过compiler::cmpfun() 对方法进行字节编译。如果您有“普通”引用类方法,我认为这是不可能的。

  • 对于这个具体的例子来说,把它弄得那么复杂肯定没有什么意义,但我想我还是会说明这种方法。

    方法定义
    setGeneric(
    name="thisIsPublic_ref",
    signature=c(".self"),
    def=function(
    .self,
    ...
    ) {
    standardGeneric("thisIsPublic_ref")
    }
    )
    setGeneric(
    name="thisIsPrivate_ref",
    signature=c(".self"),
    def=function(
    .self,
    ...
    ) {
    standardGeneric("thisIsPrivate_ref")
    }
    )

    require(compiler)

    setMethod(
    f="thisIsPublic_ref",
    signature=signature(.self="B"),
    definition=cmpfun(function(
    .self,
    ...
    ){
    .self$b.1 * 1000
    })
    )
    setMethod(
    f="thisIsPrivate_ref",
    signature=signature(.self="B"),
    definition=cmpfun(function(
    .self,
    ...
    ){
    .self$b.2
    })
    )

    实例
    x.b <- new("B", b.1=10, b.2=TRUE)
    x.a <- new("A", a.1=x.b, a.2="hello world")

    公共(public)与私有(private)
    A 类的实例(即 x.a )应该被允许使用类 B公众 方法:
    > x.a$a.1$thisIsPublic()
    [1] 10000
    A 类的实例(即 x.a )应该 不是 允许使用类 B私有(private) 方法。所以我想要这个 不是 工作,即导致错误:
    > x.a$a.1$thisIsPrivate()
    [1] TRUE

    知道如何指定这一点吗?

    到目前为止我唯一想到的:

    添加 sender每个方法的参数,为每个方法调用显式指定它并检查是否 class(.self) == class(sender) .但这似乎有点“明确”。

    最佳答案

    由于函数是 R 中的一等对象,您可以将一个嵌入另一个对象中,如下所示:

    hello <- function() {
    print_ <- function() {
    return ('hello world')
    }
    print_()
    }

    是的,它很厚颜无耻,可能不是最干净的方式,但它确实有效......使用'hello()'调用。

    关于oop - 有没有办法为 S4 引用类声明公共(public)和私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11073253/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com