我能否创建“函数”的 S4 父类(super class)并通过函数调用访问该对象的槽?目前我有:
> setClass("pow",representation=representation(pow="numeric"),contains="function")
[1] "pow"
> z=new("pow",function(x){x^2},pow=3)
> z(2)
[1] 4
现在我真正想要的是函数是 x 的 @pow 插槽本身的幂,所以如果我这样做:
> z@pow=3
我得到立方体,如果我这样做:
> z@pow=2
我得到正方形。
但我不知道如何像在 Python 中那样获取对“self”的引用。我猜它在环境中的某个地方……
这是它在 python 中的工作方式:
class Pow:
def __init__(self,power):
self.power=power
self.__call__ = lambda x: pow(x,self.power)
p = Pow(2) # p is now a 'squarer'
print p(2) # prints 4
p.power=3 # p is now a 'cuber'
print p(2) # prints 8
再简单不过了,我什至不需要“导入反重力”……
最佳答案
诉诸一点语言操作
setClass("Pow", representation("function", pow="numeric"),
prototype=prototype(
function(x) {
self <- eval(match.call()[[1]])
x^self@pow
}, pow=2))
然后
> f = g = new("Pow")
> g@pow = 3
> f(2)
[1] 4
> g(2)
[1] 8
虽然 Spacedman 说事情可能会出错
> f <- function() { Sys.sleep(2); new("Pow") }
> system.time(f()(2))
user system elapsed
0.002 0.000 4.005
在行内多一点但偏离问题规范并且可能在眼睛上同样容易
setClass("ParameterizedFunFactory",
representation(fun="function", param="numeric"),
prototype=prototype(
fun=function(x, param) function(x) x^param,
param=2))
setGeneric("fun", function(x) standardGeneric("fun"))
setMethod(fun, "ParameterizedFunFactory",
function(x) x@fun(x, x@param))
与
> f = g = new("ParameterizedFunFactory")
> g@param = 3
> fun(f)(2)
[1] 4
> fun(g)(2)
[1] 8
关于r - 访问 S4 函数父类(super class)的槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8327926/