Menu
Coddy logo textTech

기본 메서드

Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 8번째.

어떤 메서드도 클래스와 일치하지 않으면 UseMethod()는 기본 메서드인 name.default를 찾습니다. 이는 제네릭이 알지 못하는 모든 클래스에 대한 대체 메서드입니다:

describe <- function(x) UseMethod("describe")
describe.dog <- function(x) paste("a dog called", x$name)
describe.default <- function(x) "something I do not know"
rex <- structure(list(name = "Rex"), class = "dog")
car <- structure(list(), class = "car")
print(describe(rex))
print(describe(car))

출력:

[1] "a dog called Rex"
[1] "something I do not know"

기본 메서드가 없으면 알 수 없는 클래스에 제네릭을 호출할 때 오류와 함께 중지됩니다:

describe <- function(x) UseMethod("describe")
describe.dog <- function(x) paste("a dog called", x$name)
car <- structure(list(), class = "car")
describe(car)

출력:

Error in UseMethod("describe") : 
  no applicable method for 'describe' applied to an object of class "car"
Calls: describe
Execution halted

일반 값도 디스패치됩니다. 클래스 속성이 없는 숫자에는 암시적 클래스 numeric이 있고, 텍스트에는 character가 있으며, TRUE에는 logical이 있으므로 해당 이름의 메서드는 일반 벡터에서 작동합니다:

describe <- function(x) UseMethod("describe")
describe.numeric <- function(x) paste("numbers adding up to", sum(x))
describe.character <- function(x) paste("words:", paste(x, collapse = " "))
describe.default <- function(x) "something else"
print(describe(c(1, 2, 3)))
print(describe(c("a", "b")))
print(describe(TRUE))

출력:

[1] "numbers adding up to 6"
[1] "words: a b"
[1] "something else"

기본 메서드는 정중하게 거부할 수도 있습니다. 호출자가 무엇이 잘못되었는지 알 수 있도록 클래스 이름을 지정하는 메시지와 함께 stop()을 사용하면 됩니다. class(x)[1]은 객체의 첫 번째 클래스입니다:

area <- function(shape) UseMethod("area")
area.square <- function(shape) shape$side^2
area.default <- function(shape) {
  stop("cannot compute the area of a ", class(shape)[1], call. = FALSE)
}
for (s in list(structure(list(side = 2), class = "square"), structure(list(), class = "blob"))) {
  cat(tryCatch(area(s), error = function(e) conditionMessage(e)), "\n")
}

출력:

4 
cannot compute the area of a blob 
challenge icon

챌린지

쉬움

일반 벡터에 대해 제네릭 describe(x)와 Describe.R의 메서드를 완성하세요:

  • describe.numeric()은 3 numbers, sum 6을 반환합니다.
  • describe.character()은 2 words, longest: apple을 반환합니다(동률인 경우 가장 긴 단어 중 첫 번째 단어).
  • describe.logical()은 2 of 3 are TRUE를 반환합니다.
  • describe.default()은 something else를 반환합니다.

제공된 코드는 num 1,2,3, chr apple,kiwi, lgl TRUE,FALSE,TRUE 또는 값과 함께 제공되는 다른 단어가 포함된 줄을 읽고, 이를 리스트로 변환합니다. 각 항목에 대해 describe()를 출력합니다.

코드는 Describe.R에 작성하세요. main.R에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

source("Describe.R")

# 제공된 입력/출력 코드: 있는 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  values <- strsplit(p[2], ",")[[1]]
  x <- switch(p[1],
    num = as.numeric(values),
    chr = values,
    lgl = as.logical(values),
    list(values))
  cat(describe(x), "\n", sep = "")
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러