泛型与方法

R 中的 S3 与 R6 面向对象编程

Richie Cotton

Data Evangelist at DataCamp

summary(c(TRUE, FALSE, NA, TRUE))
   Mode   FALSE    TRUE    NA's 
logical       1       2       1
summary(rgamma(1000, 1))
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
0.000354 0.276500 0.690300 1.020000 1.384000 9.664000
R 中的 S3 与 R6 面向对象编程

 

 

 

函数重载 = 依输入而变的

                                            函数行为

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.007.png

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.008.png

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.009.png

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.010.png

R 中的 S3 与 R6 面向对象编程
print
function (x, ...) 
UseMethod("print")
<bytecode: 0x1062f0870>
<environment: namespace:base>
R 中的 S3 与 R6 面向对象编程

方法命名为 generic.class

  • print.Date
  • summary.factor
  • unique.array
R 中的 S3 与 R6 面向对象编程

方法签名包含泛型签名

args(print)
function (x, ...) 
NULL
args(print.Date)
function (x, max = NULL, ...) 
NULL
R 中的 S3 与 R6 面向对象编程

 

 

 

... 在方法间传参

在泛型与方法中都包含它

R 中的 S3 与 R6 面向对象编程
print.function
function (x, useSource = TRUE, ...) 
.Internal(print.function(x, useSource, ...))
R 中的 S3 与 R6 面向对象编程
print.Date
function (x, max = NULL, ...) 
{
    if (is.null(max)) 
        max <- getOption("max.print", 9999L)
    if (max < length(x)) {
        print(format(x[seq_len(max)]), max = max, ...)
        cat(" [ reached getOption(\"max.print\") -- omitted", 
            length(x) - max, "entries ]\n")
    }
    else print(format(x), max = max, ...)
    invisible(x)
}
R 中的 S3 与 R6 面向对象编程

 

 

ch2_1-generics-and-methods.030.png

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.031.png

R 中的 S3 与 R6 面向对象编程

ch2_1-generics-and-methods.032.png

R 中的 S3 与 R6 面向对象编程

小结

  • 将函数拆分为 泛型 + 方法
  • 方法命名为 generic.class
  • 方法参数应包含泛型参数
  • 包含 ... 参数
  • 使用 lower_snake_caselowerCamelCase
R 中的 S3 与 R6 面向对象编程

Vamos praticar!

R 中的 S3 与 R6 面向对象编程

Preparing Video For Download...