Scripts as Classes
Lesson 22 of 48 in Coddy's GDScript for Python Developers course.
A GDScript file is a class, unlike a Python module that can contain many unrelated classes and free functions. extends chooses its base; class_name registers a global script name. This course gives each data type a separate snake_case file and uses RefCounted to release ordinary objects when references disappear. Instantiate with new, not a Python class call. Member values belong to instances unless declared static. Avoid native engine names such as Node or Timer for new global types. Script classes are not scene instances just because they are used by a Node.
Complete Python comparison:
class Token:
def __init__(self): self.text = "blue"
a = Token()
b = a
b.text = "gold"
print(a.text)Python output:
goldGDScript example file demo_token.gd:
class_name DemoToken
extends RefCounted
var text: String = "blue"GDScript example file main.gd:
extends Node
func _ready() -> void:
var a: DemoToken = DemoToken.new()
var b: DemoToken = a
b.text = "gold"
print(a.text)GDScript output:
goldChallenge
EasyDefine ParcelRecord with weight:int initially 0 and label:String initially empty. Solve creates two records, sets the first from [label,weight], and returns label:weight:second_weight. Fields must be independent.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in parcel_record.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
var a: ParcelRecord = ParcelRecord.new()
var b: ParcelRecord = ParcelRecord.new()
if a.weight != 0 or a.label != "": return false
a.weight = 7
if b.weight != 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for Python Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count5Objects and State
Scripts as ClassesInitializationInstance MethodsRecap: Independent BasketsProperty SettersPractice on your own: Online GDScript compiler