Menu
CoddyTech

The self Keyword

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 4 of 65.

A function declared in a class runs on one particular object: the one before the dot in the call. Inside the function, the keyword self refers to that object.

# car.gd
class_name Car
extends RefCounted

var color: String = "Red"
var model: String = "Sedan"

func describe() -> void:
	print("I am a %s %s" % [self.color, self.model])

my_car.describe() runs describe() with self set to my_car, so the function reads that car's variables. You never pass self yourself:

var my_car := Car.new()
var taxi := Car.new()
taxi.color = "Yellow"
my_car.describe() # I am a Red Sedan
taxi.describe() # I am a Yellow Sedan

Writing self. is optional. Inside a class function, color on its own already means the object's color, so print("I am a %s %s" % [color, model]) does the same.

You need self when a parameter has the same name as a variable of the class. Inside the function the name means the parameter, and self. picks the object's variable:

func repaint(color: String) -> void:
	self.color = color

Without self., the line color = color copies the parameter onto itself, and the car keeps its old color.

challenge icon

Challenge

Easy

Complete the two functions of the class Car in car.gd:

  • set_info(year, make, model) stores its three parameters in the car's variables of the same names
  • describe() returns This car is a YEAR MAKE MODEL, for example This car is a 2020 Toyota Corolla

The supplied code reads how many cars follow, then one line per car (year make model). It creates each car, calls set_info(), and prints describe() for every car. For the line 2020 Toyota Corolla it prints:

This car is a 2020 Toyota Corolla

Your code goes in car.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 count := int(OS.read_string_from_stdin())
	var cars: Array[Car] = []
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var car := Car.new()
		car.set_info(int(parts[0]), parts[1], parts[2])
		cars.append(car)
	for car in cars:
		print(car.describe())
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