Quoting Peng Yu <pengyu...@gmail.com>:

In the following code, 'multiply' doesn't multiply a...@x by 2. I'm
wondering how to define a method that can change the slot of a class.

$ Rscript setGeneric.R
setClass(
+     Class='A',
+     representation=representation(
+         x='numeric'
+         )
+     )
[1] "A"

setMethod(
+     f='initialize',
+     signature='A',
+     definition=function(.Object,x){
+       cat("~~~ A: initializator ~~~\n")
+       .Object<-callNextMethod(.Object,x=x)
+       return(.Object)
+     }
+     )
[1] "initialize"

setGeneric(
+     name='multiply',
+     def=function(object){
+       standardGeneric('multiply')
+     }
+     )
[1] "multiply"

setMethod(
+     f='multiply',
+     signature='A',
+     definition=function(object){
+       obj...@x=object@x*2
+     }
+     )

Remember that R has 'copy on change' semantics, so obj...@x = obj...@x^2 creates a (seemingly -- we don't 'know' what is going on underneath) new instance of object, and assigns the value of obj...@x^2 to its 'x' slot. So the original 'object' is unchanged. If you return object,

setMethod(multiply, "A", function(object) {
    obj...@x = obj...@x^2
    object
})

then

  a = multiply(a)

will update the value of a. It is worth noting the implied copying going on here, and the implications for performance.

R.oo and proto will provide a more familiar paradigm (though perhaps no less copying, in general).

Martin


[1] "multiply"

a=new(Class='A',x=10)
~~~ A: initializator ~~~
multiply(a)
print(a...@x)
[1] 10

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to