Instance vs Static Variables
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 9 of 65.
A normal var in a class is an instance variable: each object has its own. A static var belongs to the class instead: there is one value, shared by every object.
# student.gd
class_name Student
extends RefCounted
static var school: String = "Godot High"
static var count: int = 0
var student_name: String
func _init(new_name: String) -> void:
student_name = new_name
count += 1var ada := Student.new("Ada")
var bo := Student.new("Bo")
print(Student.count) # 2
print(ada.student_name, " and ", bo.student_name) # Ada and Bo
Student.school = "Godot Academy"
print(ada.school) # Godot Academy
print(bo.school) # Godot AcademyRead a static variable through the class name, as in Student.count, with no object needed. Inside the class, use its name: count += 1 in _init() counts every student created so far.
Changing Student.school changes it for every student at once. ada.school = "Night School" would do the same, because there is only one school; writing the class name makes that clear.
A const is shared the same way but can never change. Use a static var for shared data that changes while the program runs, such as a counter or a setting all objects follow.
Challenge
EasyComplete the class BankAccount in bank_account.gd:
- a static
intvariableinterest_percentthat starts at2, shared by all accounts - a static
intvariableaccount_countthat starts at0; the constructor adds1to it for every new account describe()returnsHOLDER: $BALANCE at PERCENT%, using the account'sholderandbalanceand the sharedinterest_percent
The supplied code reads how many accounts follow and one holder balance line each, then a new interest rate. It prints BankAccount.account_count and every account, sets BankAccount.interest_percent to the new rate, and prints every account again. For Alice 1000, Bob 2000 and the rate 3 it prints:
Accounts opened: 2
Alice: $1000 at 2%
Bob: $2000 at 2%
After the rate change:
Alice: $1000 at 3%
Bob: $2000 at 3%Your code goes in bank_account.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 accounts: Array[BankAccount] = []
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
accounts.append(BankAccount.new(parts[0], int(parts[1])))
print("Accounts opened: %d" % BankAccount.account_count)
for account in accounts:
print(account.describe())
BankAccount.interest_percent = int(OS.read_string_from_stdin())
print("After the rate change:")
for account in accounts:
print(account.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