6.1 Two types of OOP system
6.1.1 Encapsulated OOP
- Python, C++, Java, RC & R6 in R…
- Methods belong to the objects or classes.
- Syntax to call a specific method:
object.method(arg1, arg2, …)
.
- The class encapsulates both data(fields) and behaviors(methods).
6.1.2 Generic function OOP
- S3 & S4 in R
- Methods belong to generic functions.
- The class only encapsulates data - do not keep methods information.
- The generic function looks at the object’s class and behaves differently based on the class.
- 一个特定的泛型函数,吃类A的对象,其执行的操作为A流程——相当于类A自己的方法;吃B的对象,其执行的操作为B流程——相当于类B自己的方法……
- Method dispatch is the process to find the correct method given a class.
- In S3 and S4, polymorphic functions are used as generic functions.
- Polymorphic functions behave differently for different input types
6.2 S3
6.2.1 Behind the generics
As we mentioned above, in S3, methods belong to function, which is called generic functions.
If a call to UseMethod()
can be found in the source code of a function, then this function is a generic function. It is the function that figures out the correct method to call, the process of method dispatch.
>>> mean
function (x, ...)
UseMethod("mean")
<bytecode: 0x127f01628>
<environment: namespace:base>
What the generic function really does is to find and call a function named <generic>.<class>
according to the class of the input. For example, Date
method for the mean()
generic is called mean.Date()
.
6.2.2 Testing generics