상속 체인
Coddy GDScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 65개 중 18번째.
자식 클래스 자체가 부모 클래스가 될 수도 있습니다. 각 extends는 상속 체인에 한 단계씩 추가합니다:
# vehicle.gd
class_name Vehicle
extends RefCounted
var wheels: int
func _init(w: int) -> void:
wheels = w
func describe() -> String:
return "%d wheels" % wheels# car.gd
class_name Car
extends Vehicle
func _init() -> void:
super(4)
func describe() -> String:
return "Car with " + super()# race_car.gd
class_name RaceCar
extends Car
var top_speed: int
func _init(speed: int) -> void:
super()
top_speed = speed
func describe() -> String:
return super() + ", top speed %d" % top_speedRaceCar에는 Car와 Vehicle의 모든 기능이 있습니다. 각 super()는 한 단계 위로 올라가므로, 한 번 호출하면 describe()의 세 가지 버전이 모두 실행됩니다:
print(RaceCar.new(300).describe())Car with 4 wheels, top speed 300메서드를 호출하거나 변수를 읽을 때 Godot은 먼저 객체 자체의 클래스에서 찾고, 그다음 부모 클래스에서, 이어서 부모의 부모 클래스에서 찾으며, 처음 발견한 것을 사용합니다. RaceCar.new(300).wheels는 두 단계 위에 있는 Vehicle에서 찾을 수 있습니다.
모든 클래스에는 부모 클래스가 정확히 하나 있습니다. extends는 클래스 하나만 받으며, 두 개를 나열하면 구문 분석 오류가 발생합니다:
class_name FlyingCar
extends Car, PlaneParse Error: Expected end of statement after superclass, found "," instead.GDScript에는 다중 상속이 없습니다. 클래스에 두 클래스의 기능이 모두 필요하다면, 이들을 하나의 상속 계층에 배치하거나 다른 클래스의 객체를 전달해 함께 작업하도록 하세요(이 내용은 뒤에서 다룹니다).
챌린지
쉬움character.gd에는 완성된 Character 클래스가 있습니다. 여기에는 이름, hp, NAME (HP HP)를 반환하는 describe(), 1을 반환하는 attack()이 포함됩니다. 이를 기반으로 두 단계 더 만드세요.
Warrior는Character를 상속하고strength를 추가합니다. 생성자는 이름과 hp를super()에 전달합니다.describe()는 부모 클래스의 텍스트에, strength S를 추가하고,attack()은 strength를 반환합니다.Knight는Warrior를 상속하고armor를 추가합니다. 생성자는 이름, hp, strength를super()에 전달합니다.describe()는Warrior의 텍스트에, armor A를 추가하고,attack()은Warrior의 공격력에5를 더한 값을 반환합니다.
제공된 코드는 이어지는 캐릭터 수를 읽은 다음, 캐릭터마다 한 줄씩 읽습니다. 형식은 character NAME HP, warrior NAME HP STRENGTH 또는 knight NAME HP STRENGTH ARMOR입니다. 이 코드는 describe()와 공격력을 출력합니다. knight Arthur 120 15 8의 경우 다음을 출력합니다.
Arthur (120 HP), strength 15, armor 8
Attack: 20코드는 warrior.gd와 knight.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
extends Node
func _ready():
# 제공된 입출력 코드: 그대로 두세요
var count := int(OS.read_string_from_stdin())
for i in count:
var p := OS.read_string_from_stdin().split(" ")
var c: Character
if p[0] == "knight":
c = Knight.new(p[1], int(p[2]), int(p[3]), int(p[4]))
elif p[0] == "warrior":
c = Warrior.new(p[1], int(p[2]), int(p[3]))
else:
c = Character.new(p[1], int(p[2]))
print(c.describe())
print("Attack: %d" % c.attack())
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 GDScript 컴파일러