# Accessing slots of an S4 function superclass

Can I create an S4 superclass of "function" and access the slots of that object from the function call? At the moment I have:

```> setClass("pow",representation=representation(pow="numeric"),contains="function")
[1] "pow"
> z=new("pow",function(x){x^2},pow=3)
> z(2)
[1] 4
```

Now what I really want is for the function to be x to the power of the @pow slot of itself, so if I then do:

```> z@pow=3
```

I get cubes, and if I do:

```> z@pow=2
```

I get squares.

But I don't see how to get a reference to 'self' like I would do in Python. I'm guessing its somewhere in the environment somewhere...

Here's how it works in 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
```

Couldn't really be easier, and I didn't even have to do "import antigravity"....

Resorting to a little language manipulation

```setClass("Pow", representation("function", pow="numeric"),
prototype=prototype(
function(x) {
self <- eval(match.call()[[1]])
x^self@pow
}, pow=2))
```

and then

```> f = g = new("Pow")
> g@pow = 3
> f(2)
[1] 4
> g(2)
[1] 8
```

although as Spacedman says things can go wrong

```> f <- function() { Sys.sleep(2); new("Pow") }
> system.time(f()(2))
user  system elapsed
0.002   0.000   4.005
```

A little more within the lines but deviating from the problem specification and probably no less easy on the eyes is

```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))
```

with

```> f = g = new("ParameterizedFunFactory")
> g@param = 3
> fun(f)(2)
[1] 4
> fun(g)(2)
[1] 8
```