Menu
Coddy logo textTech

contains로 확장하기

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

contains = "Animal"은 새로운 S4 클래스를 Animal의 하위 클래스로 만듭니다. 하위 클래스에는 부모 클래스의 모든 슬롯과 자체 슬롯이 포함되며, new()는 이 슬롯을 모두 받습니다:

setClass("Animal", slots = c(name = "character", age = "numeric"))
setClass("Dog", contains = "Animal", slots = c(breed = "character"))
rex <- new("Dog", name = "Rex", age = 3, breed = "collie")
print(slotNames("Dog"))
cat(rex@name, rex@breed)

출력:

[1] "breed" "name"  "age"  
Rex collie

부모를 위해 작성된 메서드는 자식에게도 적용됩니다. 제네릭에 Dog을 위한 메서드가 없으면 S4는 Animal을 위한 메서드를 사용합니다:

setClass("Animal", slots = c(name = "character"))
setClass("Dog", contains = "Animal")
invisible(setGeneric("intro", function(a) standardGeneric("intro")))
setMethod("intro", "Animal", function(a) paste("I am", a@name))
print(intro(new("Dog", name = "Rex")))

출력:

[1] "I am Rex"

자식 클래스는 동일한 제네릭에 대해 고유한 메서드를 정의하여 부모 메서드를 재정의합니다. 가장 구체적인 클래스가 우선하며, 다른 하위 클래스는 부모의 메서드를 유지합니다:

setClass("Animal", slots = c(name = "character"))
setClass("Dog", contains = "Animal")
setClass("Cat", contains = "Animal")
invisible(setGeneric("sound", function(a) standardGeneric("sound")))
setMethod("sound", "Animal", function(a) "...")
setMethod("sound", "Dog", function(a) "woof")
cat(sound(new("Dog", name = "Rex")), sound(new("Cat", name = "Tom")))

출력:

woof ...

개에 대해 is(x, "Animal")은 TRUE이고, "Animal"로 선언된 슬롯은 Dog를 허용합니다. 부모 클래스용으로 작성된 코드는 모든 하위 클래스에서 작동합니다:

setClass("Animal", slots = c(name = "character"))
setClass("Dog", contains = "Animal")
setClass("Owner", slots = c(pet = "Animal"))
rex <- new("Dog", name = "Rex")
o <- new("Owner", pet = rex)
cat(is(rex, "Animal"), is(o@pet, "Dog"))

출력:

TRUE TRUE
challenge icon

챌린지

쉬움

직원과 관리자는 두 파일에 정의된 S4 클래스입니다. Employee.R에서는 Employee(슬롯 name, salary)와 제네릭 describe()를 선언하며, Bo earns 40000을 반환하는 Employee용 메서드가 필요합니다. Manager.R에서는 Employee를 포함하고 reports 슬롯(numeric)을 추가하는 Manager를 선언하며, describe()를 재정의하여 Ada earns 60000 and manages 4를 반환하도록 합니다.

제공된 코드는 employee Bo 40000 또는 manager Ada 60000 4 형식의 줄을 읽고, describe()의 결과와 객체가 직원인지 여부 및 해당 슬롯을 출력합니다.

코드는 Employee.R과 Manager.R에 작성합니다. main.R에는 제공된 입출력 코드가 있으며 편집할 수 없습니다.

직접 해보기

source("Employee.R")
source("Manager.R")

# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  x <- if (p[1] == "manager") {
    new("Manager", name = p[2], salary = as.numeric(p[3]), reports = as.numeric(p[4]))
  } else {
    new("Employee", name = p[2], salary = as.numeric(p[3]))
  }
  cat(describe(x), "\n", sep = "")
  cat("is an employee: ", is(x, "Employee"), ", slots: ", paste(slotNames(x), collapse = ", "), "\n", sep = "")
}
quiz icon실력 점검

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

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

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