泛型與方法

在 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 的物件導向程式設計

第 2 章:泛型與方法(ch2_1-generics-and-methods.007.png)

在 R 中使用 S3 與 R6 的物件導向程式設計

第 2 章:泛型與方法(ch2_1-generics-and-methods.008.png)

在 R 中使用 S3 與 R6 的物件導向程式設計

第 2 章:泛型與方法(ch2_1-generics-and-methods.009.png)

在 R 中使用 S3 與 R6 的物件導向程式設計

第 2 章:泛型與方法(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 的物件導向程式設計

一起來練習吧!

在 R 中使用 S3 與 R6 的物件導向程式設計

Preparing Video For Download...