Constructor (_init)
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 7 of 65.
Setting every property after new() takes several lines, and it is easy to forget one. A constructor sets an object up as it is created. In GDScript the constructor is the method _init():
# book.gd
class_name Book
extends RefCounted
var title: String
var author: String
var pages: int
func _init(book_title: String, book_author: String, page_count: int) -> void:
title = book_title
author = book_author
pages = page_countThe arguments you pass to new() go to _init(), which runs automatically before new() returns the object:
var dune := Book.new("Dune", "Frank Herbert", 412)
print(dune.title) # Dune
print(dune.pages) # 412When _init() has parameters, new() must pass them: Book.new() with no arguments is an error reported before the program runs. A parameter with a default value is optional:
func _init(book_title: String, book_author: String = "Unknown") -> void:With this constructor, Book.new("Notes") creates a book whose author is "Unknown".
The parameter names above differ from the property names. If they were the same, you would write self.title = title, as in the lesson on self.
Challenge
EasyComplete the class Book in book.gd:
- the constructor
_init(book_title, book_author, page_count)stores its arguments in the propertiestitle,authorandpages describe()returns'TITLE' by AUTHOR, PAGES pages, with the title in single quotes
The supplied code reads how many books follow, then one line per book with the title, author and page count separated by ;. It creates each book with Book.new(), prints describe(), and finally prints the total of the pages properties. For the line Dune;Frank Herbert;412 it prints:
'Dune' by Frank Herbert, 412 pages
Total pages: 412Your code goes in book.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 total := 0
for i in count:
var parts := OS.read_string_from_stdin().split(";")
var book := Book.new(parts[0], parts[1], int(parts[2]))
print(book.describe())
total += book.pages
print("Total pages: %d" % total)
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