Menu
CoddyTech

S3 상속 순서

Coddy의 GDScript 개발자를 위한 R 코스 레슨. 48개 중 39번째.

GDScript의 extends와 super는 클래스 상속과 부모 동작에 대한 명시적 위임을 제공합니다. 반면 R S3 디스패치는 정렬된 클래스 이름 벡터를 따르며, NextMethod는 그 체인을 이어 갑니다. 확장 메서드가 다음 결과를 대체하거나 실수로 반복하지 않고 한 번 결합하는지 테스트하세요.

GDScript

extends SceneTree
class Base:
    var price = 5
    func total(quantity):
        return price * quantity
class Delivery extends Base:
    var fee = 2
    func total(quantity):
        return super.total(quantity) + fee
func _init():
    var delivery = Delivery.new()
    print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
    quit()

R

sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")

S3 클래스 순서는 디스패치 체인에 영향을 줍니다.

challenge icon

챌린지

쉬움

일반적인 fee(x)를 정의하세요. parcel 메서드는 x$units*2를 반환합니다. urgent 메서드는 NextMethod()+5를 반환합니다. 어댑터는 입력 플래그가 1이면 클래스 c("urgent","parcel")를 만들고, 그렇지 않으면 클래스 parcel을 만듭니다. 입력은 음이 아닌 단위 수 뒤에 플래그 0 또는 1이 오는 형식입니다.

선언된 공개 API를 유지하세요. 화면에 보이는 잠금 드라이버는 solve(lines)를 출력할 뿐 아니라 API를 직접 검사합니다. 입력은 명시된 계약을 만족하며 모든 산술 연산의 결과는 작고 유한합니다.

코드는 Parcel.R 및 Exercise.R에 작성하세요. main.R은 종속 항목을 순서대로 불러오며 제공된 입력/출력 코드를 담고 있습니다. 이 파일은 수정할 수 없습니다.

직접 해보기

source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon실력 점검

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

GDScript 개발자를 위한 R의 모든 레슨

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