callNextMethod
Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 33번째.
S4 메서드 내부에서 callNextMethod()는 동일한 인수를 사용해 부모 클래스의 메서드를 호출하고 그 결과를 반환합니다. 자식 메서드는 부모의 답변을 반복하는 대신 그 위에 기능을 추가합니다:
setClass("Employee", slots = c(name = "character", salary = "numeric"))
setClass("Manager", contains = "Employee", slots = c(reports = "numeric"))
invisible(setGeneric("describe", function(x) standardGeneric("describe")))
setMethod("describe", "Employee", function(x) paste(x@name, "earns", x@salary))
setMethod("describe", "Manager", function(x) paste(callNextMethod(), "and manages", x@reports))
print(describe(new("Manager", name = "Ada", salary = 60000, reports = 4)))출력:
[1] "Ada earns 60000 and manages 4"show()에서도 작동합니다. 자식 클래스가 부모의 줄을 출력한 다음 자신의 줄을 출력합니다:
setClass("Employee", slots = c(name = "character"))
setClass("Manager", contains = "Employee", slots = c(reports = "numeric"))
setMethod("show", "Employee", function(object) cat("Employee:", object@name, "\n"))
setMethod("show", "Manager", function(object) {
callNextMethod()
cat("Reports:", object@reports, "\n")
})
new("Manager", name = "Ada", reports = 4)출력:
Employee: Ada
Reports: 4 new()는 제네릭 initialize()를 호출합니다. 이를 위한 메서드는 다른 슬롯으로부터 계산되는 슬롯을 채울 수 있습니다. 먼저 callNextMethod(.Object, ...)를 호출하므로 일반적인 설정과 유효성 검사가 계속 수행됩니다.
setClass("Order", slots = c(prices = "numeric", total = "numeric"))
setMethod("initialize", "Order", function(.Object, ...) {
.Object <- callNextMethod(.Object, ...)
.Object@total <- sum(.Object@prices)
.Object
})
o <- new("Order", prices = c(2.5, 4, 1))
print(o@total)출력:
[1] 7.5S3의 NextMethod()처럼 callNextMethod()는 여러 수준을 거치며 연결되고, 각 클래스는 자신의 부분을 추가합니다:
setClass("Ticket", slots = c(base = "numeric"))
setClass("Vip", contains = "Ticket")
setClass("Backstage", contains = "Vip")
invisible(setGeneric("price", function(t) standardGeneric("price")))
setMethod("price", "Ticket", function(t) t@base)
setMethod("price", "Vip", function(t) callNextMethod() * 2)
setMethod("price", "Backstage", function(t) callNextMethod() + 50)
cat(price(new("Ticket", base = 30)), price(new("Vip", base = 30)), price(new("Backstage", base = 30)))출력:
30 60 110챌린지
쉬움티켓은 세 가지 등급으로 나뉘며, 각 등급은 고유한 파일에 있습니다. 클래스와 제네릭 price()가 선언되어 있습니다. 메서드를 추가하세요:
Ticket.R:price()는 기본 가격을 반환하고,show()는Ticket for gala와 줄바꿈을 출력합니다.Vip.R:price()는 티켓 가격의 1.5배이고,show()는 티켓 행을 출력한 다음VIP lounge access를 출력합니다.Backstage.R:price()는 VIP 가격에 50을 더한 값이고,show()는 VIP 행을 출력한 다음Backstage pass를 출력합니다.
서브클래스 메서드에서 callNextMethod()를 사용하세요. 제공된 코드는 vip gala 80(등급, 이벤트, 기본 가격) 형식의 줄을 읽고 각 티켓과 가격을 출력합니다.
코드는 Ticket.R, Vip.R, Backstage.R에 작성하세요. main.R에는 제공된 입출력 코드가 들어 있으며 수정할 수 없습니다.
직접 해보기
source("Ticket.R")
source("Vip.R")
source("Backstage.R")
# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
p <- strsplit(line, " ")[[1]]
base <- as.numeric(p[3])
t <- switch(p[1],
standard = new("Ticket", event = p[2], base = base),
vip = new("VipTicket", event = p[2], base = base),
backstage = new("BackstageTicket", event = p[2], base = base))
print(t)
cat(sprintf("price: %.2f", price(t)), "\n", sep = "")
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러