Menu
CoddyTech

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 * height
var r := Rectangle.new()
print(r.area) # 12
r.width = 10
print(r.area) # 30

r.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 / 9
t.celsius = 25.0
print(t.fahrenheit) # 77.0
t.fahrenheit = 98.6
print(t.celsius) # 37.0

A 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 icon

Challenge

Easy

Complete the class Temperature in temperature.gd. It stores one value, celsius, and computes the other scales from it:

  • fahrenheit: the getter returns celsius * 9 / 5 + 32, and the setter stores (value - 32) * 5 / 9 in celsius
  • kelvin: a read-only property whose getter returns celsius + 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 K

Your 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])
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler