Menu
CoddyTech

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를 선언하고, Ada earns 60000 and manages 4을 반환하도록 describe()를 재정의합니다.

제공된 코드는 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 컴파일러