No there is no standard way of doing this from inside your class definition as you would do in python.
In python you would do something like MyObject.my_method()
while in R with S3 or S4 this would be my_method(MyObject)
so it looks exactly like my_function(MyObject)
. The only difference is that under the hood the function you called dispatches the call to the adequate method. Defining these methods for multiple classes is done as follows:
mean <- function (x, ...) UseMethod("mean", x)
mean.numeric <- function(x, ...) sum(x) / length(x)
mean.data.frame <- function(x, ...) sapply(x, mean, ...)
mean.matrix <- function(x, ...) apply(x, 2, mean)
mean.default <- function(x, ...) {
# do something
}
However, if you call the mean function on a class for which no method has been defined, it is up to the function to handle this, not to the class.
Then you have RC and S6 objects which have a more python-like syntax (MyObject$my_method()
), however they would just throw an error that there is no corresponding field or method for the class you used.
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
"my_method" is not a valid field or method name for reference class “MyObject”
Here some infos about OO-programing in R.