가상 클래스
Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 34번째.
가상 클래스는 여러 클래스에 공통된 내용을 설명하며, 자체적으로 객체를 가질 수 없습니다. representation("VIRTUAL")로 선언하고, 하위 클래스에서는 일반적인 방식으로 contains를 사용합니다:
setClass("Shape", representation("VIRTUAL"))
setClass("Circle", contains = "Shape", slots = c(r = "numeric"))
setClass("Square", contains = "Shape", slots = c(side = "numeric"))
cat(isVirtualClass("Shape"), is(new("Circle", r = 1), "Shape"), "\n")
cat(tryCatch({ new("Shape"); "made" }, error = function(e) "not allowed"), "\n")출력:
TRUE TRUE
not allowed 가상 클래스의 메서드는 모든 하위 클래스에서 작동합니다. 여기서 Shape에 대한 describe()는 각 하위 클래스가 구현하는 area()를 호출하므로 설명을 한 번만 작성합니다:
setClass("Shape", representation("VIRTUAL"))
setClass("Circle", contains = "Shape", slots = c(r = "numeric"))
setClass("Square", contains = "Shape", slots = c(side = "numeric"))
invisible(setGeneric("area", function(s) standardGeneric("area")))
invisible(setGeneric("describe", function(s) standardGeneric("describe")))
setMethod("area", "Circle", function(s) pi * s@r^2)
setMethod("area", "Square", function(s) s@side^2)
setMethod("describe", "Shape", function(s) sprintf("%s with area %.2f", class(s), area(s)))
for (s in list(new("Circle", r = 1), new("Square", side = 2))) cat(describe(s), "\n")출력:
Circle with area 3.14
Square with area 4.00 가상 클래스는 슬롯을 선언할 수 있으며, 그러면 모든 하위 클래스가 해당 슬롯을 갖습니다:
setClass("Shape", representation("VIRTUAL", label = "character"))
setClass("Square", contains = "Shape", slots = c(side = "numeric"))
sq <- new("Square", label = "tile", side = 2)
print(slotNames("Square"))출력:
[1] "side" "label"setClassUnion()은 기존 클래스들로 가상 클래스를 만듭니다. 해당 타입의 슬롯은 그중 어느 것이든 허용하므로, 이메일 주소나 전화번호 중 하나인 연락처를 지정할 수 있습니다:
setClassUnion("Contact", c("character", "numeric"))
setClass("Friend", slots = c(name = "character", contact = "Contact"))
a <- new("Friend", name = "Ada", contact = "ada@x.org")
b <- new("Friend", name = "Bo", contact = 5550123)
cat(class(a@contact), class(b@contact), "\n")
cat(tryCatch({ new("Friend", name = "Cy", contact = TRUE); "ok" }, error = function(e) "refused"), "\n")출력:
character numeric
refused 챌린지
쉬움결제는 가상 클래스 Payment(슬롯 amount)와 제네릭 fee() 및 receipt()를 공유하며, 모두 Payment.R에 있습니다. 다음을 완성하세요:
Payment.R에서Payment를 위한receipt()메서드: 클래스 이름을 소문자로 변환한 값,amount및fee()로 구성되는card: 100.00 + 2.00 fee;Card.R에서Card클래스(Payment을 포함)와 해당fee(): 금액의 2%;Cash.R에서Cash클래스와 해당fee(): 0.
제공된 코드는 card 100 또는 cash 20 형식의 줄을 읽고, 각 영수증과 총 청구 금액을 출력한 다음 Payment가 가상이며 생성될 수 없는지 확인합니다.
코드는 Payment.R, Card.R 및 Cash.R에 작성합니다. main.R에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
source("Payment.R")
source("Card.R")
source("Cash.R")
# 제공된 입력/출력 코드: 있는 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
total <- 0
for (line in input) {
p <- strsplit(line, " ")[[1]]
amount <- as.numeric(p[2])
pay <- switch(p[1], card = new("Card", amount = amount), cash = new("Cash", amount = amount))
cat(receipt(pay), "\n", sep = "")
total <- total + amount + fee(pay)
}
cat(sprintf("charged: %.2f", total), "\n", sep = "")
cat("Payment is virtual: ", isVirtualClass("Payment"), "\n", sep = "")
cat(tryCatch({ new("Payment", amount = 1); "created a Payment" }, error = function(e) "cannot create a Payment"), "\n", sep = "")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러