Property Getters
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 12 of 65.
A get: block, the property's getter, runs every time the property is read, and what it returns is the value the reader gets. Use it for a value computed from other properties:
# rectangle.gd
var width: int = 4
var height: int = 3
var area: int:
get:
return width * heightvar r := Rectangle.new()
print(r.area) # 12
r.width = 10
print(r.area) # 30r.area is read like a variable, without parentheses, but it is computed again on every read, so it always matches the current width and height.
A property can have both blocks. Here fahrenheit only converts: reading it converts from celsius, and assigning it converts back and stores the result in celsius:
# temperature.gd
var celsius: float = 0.0
var fahrenheit: float:
get:
return celsius * 9 / 5 + 32
set(value):
celsius = (value - 32) * 5 / 9t.celsius = 25.0
print(t.fahrenheit) # 77.0
t.fahrenheit = 98.6
print(t.celsius) # 37.0A property with only get: is read-only by convention. Assigning to it is not an error, but the getter ignores what was assigned: after r.area = 100, r.area still returns 30.
Challenge
EasyComplete the class Temperature in temperature.gd. It stores one value, celsius, and computes the other scales from it:
fahrenheit: the getter returnscelsius * 9 / 5 + 32, and the setter stores(value - 32) * 5 / 9incelsiuskelvin: a read-only property whose getter returnscelsius + 273.15
The supplied code reads how many commands follow, then one per line: c VALUE sets celsius and f VALUE sets fahrenheit. After each command it prints the three properties with two decimals. For c 25, f 98.6 and c -40 it prints:
25.00 C | 77.00 F | 298.15 K
37.00 C | 98.60 F | 310.15 K
-40.00 C | -40.00 F | 233.15 KYour code goes in temperature.gd. main.gd holds the supplied input/output code and cannot be edited.
Try it yourself
extends Node
func _ready():
# Supplied input/output code: keep it as it is
var temp := Temperature.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
if parts[0] == "c":
temp.celsius = float(parts[1])
else:
temp.fahrenheit = float(parts[1])
print("%.2f C | %.2f F | %.2f K" % [temp.celsius, temp.fahrenheit, temp.kelvin])
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler