I have struggled with this in the past and am still trying to understand what OOP really means in the context of R. I have some specific questions based on this post on the Win-Vector blog post about S3 classes / methods.
It seems to me that in R the structure containing the data, the class name and the methods applicable for this class are all different things, and in the S3 model - for convenience.
( Class names and objects ) The class attribute of an object R is a regular symbolic attribute, and any class can be assigned to any object regardless of content or even content slots. AFAIK, this will not be allowed in classic OOP languages such as C ++ or Java (what exactly mechanism stops this in C ++?). The object must conform to the structure defined during the class definition in order to have the class name.
What are the consequences of this separation of the class name and object structure?
str1 = structure(list(slot1 = "a", slot2 = "b"))
class(str1) = "myclass"
class(str1) = "some_exotic_class"
( Inheritance ). When we move on to the methods applicable to any class, there is another level of fragmentation. Inheritance is not inferred, but the object must explicitly specify class names to apply the methods corresponding to this class.
add = function(...) UseMethod("add")
add.list = function(somelist) {
Reduce(paste0, somelist)
}
str1 = structure(list(slot1 = "a", slot2 = "b"))
add(str1)
str2 = structure(list(slot1 = "a", slot2 = "b"), class = "mystr")
add(str2)
() ? , R ( - S3, R- ), ? - ? Python, , .
(Mutability) , ? , ? ? ?
str3 = structure(list(1, 2, 3), class = "my_number_class")
incrementOne = function(...) UseMethod("incrementOne")
incrementOne.my_number_class = function(somelist) lapply(somelist, function(x) x+1)
incrementOne(str3)
str3 # the values of str3 have not changed *in situ*
, , incrementOne . , R. . ?
(S3 ?) , S3? S3?
.