Static Functions
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 10 of 65.
A static func belongs to the class, like a static variable. You call it through the class name, with no object, as you did in the lesson on files: Greeter.greet("Ada"). A class can mix static functions with ordinary methods:
# student.gd
class_name Student
extends RefCounted
static var count: int = 0
var student_name: String
var score: int
func _init(new_name: String, new_score: int) -> void:
student_name = new_name
score = new_score
count += 1
static func is_passing(points: int) -> bool:
return points >= 60
static func from_line(line: String) -> Student:
var parts := line.split(" ")
return Student.new(parts[0], int(parts[1]))print(Student.is_passing(72)) # true
var ada := Student.from_line("Ada 91")
print(ada.score) # 91
print(Student.count) # 1A static function runs without an object, so it cannot use instance variables or self: score inside is_passing() is an error reported before the program runs. It can use its parameters, constants, static variables and other static functions.
from_line() shows a common use: a static function that builds and returns an object, here from a line of text. It is a second way to create a Student, next to Student.new().
You can also call a static function on an object, as in ada.is_passing(50), but the class name makes it clear that no object is involved.
Challenge
EasyWrite the grading code in two classes.
Grader in grader.gd has only static functions:
letter(points)returns"A"for 90 or more,"B"for 80 or more,"C"for 70 or more,"D"for 60 or more, and"F"below thatis_passing(points)returnstruefor 60 or more
Student in student.gd already has its properties and constructor. Complete:
- the static function
from_line(line), which splits a line such asAda 91at the space and returns a newStudentwith that name and score - the method
report(), which returnsNAME: SCORE (LETTER), passedorNAME: SCORE (LETTER), failed, using the twoGraderfunctions
The supplied code reads how many students follow, creates each one with Student.from_line(), prints its report, and finally counts the passing students. For Ada 91, Bo 42 and Cy 75 it prints:
Ada: 91 (A), passed
Bo: 42 (F), failed
Cy: 75 (C), passed
Passed: 2 of 3Your code goes in grader.gd and student.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 passed := 0
for i in count:
var student := Student.from_line(OS.read_string_from_stdin())
print(student.report())
if Grader.is_passing(student.score):
passed += 1
print("Passed: %d of %d" % [passed, count])
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