Methods
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 5 of 65.
A function declared inside a class is a method: something the objects of the class can do. Like any function, a method can take parameters and return a value, and it can read and change the object's variables:
# score_board.gd
class_name ScoreBoard
extends RefCounted
var points: int = 0
func greet() -> void:
print("Scoreboard ready")
func add(amount: int) -> void:
points += amount
func doubled() -> int:
return points * 2
func add_bonus() -> int:
add(10)
return pointsCall a method on an object with a dot and pass the arguments in the parentheses:
var board := ScoreBoard.new()
board.greet() # Scoreboard ready
board.add(5)
print(board.doubled()) # 10
print(board.add_bonus()) # 15Inside the class, a method calls another method of the same object by its name: add(10) in add_bonus() means self.add(10).
A method declared with -> void returns nothing, and one declared with -> int must return an int. Each call works on its own object: board.add(5) changes board.points and no other scoreboard.
The call must match the declaration: board.add() without an argument is an error reported before the program runs.
Challenge
EasyComplete the methods of the class BankAccount in bank_account.gd. The account keeps its money in the variable balance, which starts at 0.
deposit(amount)addsamountto the balancewithdraw(amount)subtractsamountand returnstrue. Whenamountis more than the balance, it changes nothing and returnsfalseget_balance()returns the balance
The supplied code reads how many commands follow, then one command per line: deposit AMOUNT or withdraw AMOUNT. It prints a line for each command and the final balance. For deposit 50 and withdraw 80 it prints:
Deposited 50
Not enough money for 80
Current balance: $50Your 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 account := BankAccount.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
var amount := int(parts[1])
if parts[0] == "deposit":
account.deposit(amount)
print("Deposited %d" % amount)
elif account.withdraw(amount):
print("Withdrew %d" % amount)
else:
print("Not enough money for %d" % amount)
print("Current balance: $%d" % account.get_balance())
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