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 SedanWriting 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 = colorWithout self., the line color = color copies the parameter onto itself, and the car keeps its old color.
Challenge
EasyComplete 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 namesdescribe()returnsThis car is a YEAR MAKE MODEL, for exampleThis 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 CorollaYour 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())
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