Menu
Coddy logo textTech

inherits()로 확인하기

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

inherits(x, "employee")는 x의 클래스 벡터 어디에든 employee가 있는지를 확인하므로 관리자에게도 TRUE입니다. class(x) == "employee"와 비교하면 각 위치를 개별적으로 확인하여 벡터를 반환하며, 이는 if에서 사용할 수 없습니다.

m <- structure(list(), class = c("manager", "employee"))
print(inherits(m, "employee"))
print(inherits(m, "intern"))
print(class(m) == "employee")

출력:

[1] TRUE
[1] FALSE
[1] FALSE  TRUE

여러 이름이 주어졌을 때 inherits()는 객체에 그중 하나라도 있으면 TRUE를 반환합니다. which = TRUE로 설정하면 각 이름에 대해 클래스 벡터에서의 위치를 반환하며, 해당 이름이 없으면 0을 반환합니다:

p <- structure(list(), class = c("fragile", "express", "parcel"))
print(inherits(p, c("letter", "parcel")))
print(inherits(p, c("express", "letter", "parcel"), which = TRUE))

출력:

[1] TRUE
[1] 2 0 3

한 계열의 클래스에 대해서만 의미가 있는 함수는 inherits()를 사용해 인수를 확인하고, 그렇지 않으면 명확한 메시지와 함께 중지합니다:

raise <- function(x, pct) {
  if (!inherits(x, "employee")) stop("raise() needs an employee", call. = FALSE)
  x$salary <- x$salary * (1 + pct / 100)
  x
}
m <- structure(list(salary = 50000), class = c("manager", "employee"))
print(raise(m, 10)$salary)
print(tryCatch(raise(list(salary = 1), 10), error = function(e) conditionMessage(e)))

출력:

[1] 55000
[1] "raise() needs an employee"

Filter()와 inherits()를 함께 사용하면 여러 클래스가 섞인 목록에서 모든 하위 클래스를 포함하여 한 패밀리에 속하는 멤버를 선택할 수 있습니다:

staff <- list(
  structure(list(name = "Ada"), class = c("manager", "employee")),
  structure(list(name = "Bo"), class = "employee"),
  structure(list(name = "Cy"), class = c("intern", "employee")),
  structure(list(name = "Dee"), class = c("director", "manager", "employee"))
)
managers <- Filter(function(x) inherits(x, "manager"), staff)
print(vapply(managers, function(x) x$name, character(1)))

출력:

[1] "Ada" "Dee"
challenge icon

챌린지

쉬움

카탈로그에는 책, 전자책 및 DVD가 들어 있습니다. 생성자는 Item.R, Book.R, Ebook.R 및 Dvd.R에 제공되며, 전자책의 클래스는 c("ebook", "book", "item")입니다. Catalogue.R에서 inherits()를 사용하여 두 함수를 완성하세요.

  • count_of(items, kind)는 클래스 벡터의 어느 위치에든 kind를 포함하는 항목의 개수를 반환합니다.
  • titles_of(items, kind)는 해당 항목들의 제목을 원래 순서대로 반환합니다.

제공된 코드는 book Dune, ebook Emma, dvd Alien 행을 읽고 ? book을 질의한 다음 book: 2 (Dune, Emma)을 출력합니다. 일치하는 항목이 없으면 dvd: 0만 출력합니다.

코드는 Item.R, Book.R, Ebook.R, Dvd.R 및 Catalogue.R에 작성합니다. main.R에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.

직접 해보기

source("Item.R")
source("Book.R")
source("Ebook.R")
source("Dvd.R")
source("Catalogue.R")

# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
items <- list()
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  rest <- paste(p[-1], collapse = " ")
  if (p[1] == "?") {
    titles <- titles_of(items, p[2])
    shown <- if (length(titles) > 0) paste0(" (", paste(titles, collapse = ", "), ")") else ""
    cat(p[2], ": ", count_of(items, p[2]), shown, "\n", sep = "")
  } else {
    items[[length(items) + 1]] <- switch(p[1], book = new_book(rest), ebook = new_ebook(rest), dvd = new_dvd(rest))
  }
}
quiz icon실력 점검

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

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

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