상속과 Super
Coddy의 Ruby 개발자를 위한 GDScript 코스 레슨. 48개 중 27번째.
Ruby 클래스는 하나의 슈퍼클래스를 상속하며 메서드 조회에 모듈을 포함할 수 있습니다. GDScript 스크립트는 하나의 기본 클래스를 확장하며 Ruby의 모듈 포함 방식과 같은 의미 체계를 제공하지 않습니다. 두 언어 모두 super를 제공하지만, Ruby에서 괄호 없이 super를 사용하면 현재 인수를 전달하고 super()는 인수를 전달하지 않습니다. GDScript에서는 의도한 상속 메서드를 명시적으로 호출합니다. 동작을 특수화할 때는 계약을 유지하고 도우미의 종속성을 명확히 하세요.
Ruby 3.3 비교 완성하기(main.rb 실행):
class Base
def label; "base"; end
end
class Child < Base
def label; super+"!"; end
end
puts Child.new.label
Ruby 출력:
base!GDScript 예제 파일 demo_base.gd:
class_name DemoBase
extends RefCounted
func label() -> String:
return "base"GDScript 예제 파일 demo_child.gd:
class_name DemoChild
extends DemoBase
func label() -> String:
return super.label() + "!"GDScript 예제 파일 main.gd:
extends Node
func _ready() -> void:
print(DemoChild.new().label())GDScript 출력:
base!챌린지
쉬움BaseFee.cost(units:int)->int를 units*3으로 구현하세요. DiscountFee는 BaseFee를 확장하고 상속된 동작을 사용해 cost를 max(base cost-2,0)로 재정의합니다. Solve는 DiscountFee를 사용합니다.
입력은 stdin으로 전달되는 하나의 JSON 배열입니다. 잠긴 main은 이를 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 뒤에 result=를 붙여 출력하고 줄바꿈합니다. 어떤 헬퍼도 출력하면 안 됩니다. 입력 사례를 처리하기 전에 독립적인 고정 프로브로 필수 API 동작을 검증합니다. 이 프로브는 구현 스타일을 강제하지 않습니다.
코드는 base_fee.gd, discount_fee.gd, exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 타입은 이름이 지정된 파일에 두세요.
직접 해보기
extends Node
func contract_ok(data: Array) -> bool:
if BaseFee.new().cost(4) != 12 or DiscountFee.new().cost(4) != 10 or DiscountFee.new().cost(0) != 0: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 GDScript의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러