ref:https://www.datamentor.io/r-programming/object-class-introduction/
S3 Class | S4 Class | Referene Class |
---|---|---|
Lacks formal definition | Class defined using setClass() | Class defined using setRefClass() |
Objects are created by setting the class attribute | Objects are created using new() | Objects are created using generator functions |
Attributes are accessed using $ | Attributes are accessed using @ | Attributes are accessed using $ |
Methods belong to generic function | Methods belong to generic function | Methods belong to the class |
Follows copy-on-modify semantics | Follows copy-on-modify semantics | Does not follow copy-on-modify semantics |
关于R的OOP,还有几个概念:
- OOP有两个主要的范式,
- encapsulated OOP, 封装了methods和fields,函数调用形式是object.method(arg1, arg2)
- functional OOP, methods是泛函数,调用形式是:generic(object, arg2, arg3)。 R语言才用的正是第二种范式。
- 为什么从S3 S4开始? S3和S4命名是根据S语言的版本命名的,S1和S2版本没有OOP的框架。
判断一个object是什么类型的class,可以安装使用sloop包,使用sloop::otype()
S3 VS S4
S4与S3一脉相承,但是S4比S3更加严谨正式,相对语法也更加繁琐。S4更加适合一个team协作完成一个package。