The _to_string Method
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 32 of 65.
Printing an object whose class does not define _to_string() shows only its class and an internal ID, which changes from run to run: <RefCounted#-9223372009541466673>. Define _to_string() and return the text that should appear instead:
# card.gd
class_name Card
extends RefCounted
var rank: String
var suit: String
func _init(new_rank: String, new_suit: String) -> void:
rank = new_rank
suit = new_suit
func _to_string() -> String:
return rank + " of " + suitGodot calls it every time the object is turned into text: by print(), by str(), by %s in a format string, and for each object inside a printed Array or Dictionary:
var card := Card.new("Queen", "hearts")
print(card) # Queen of hearts
print(str(card)) # Queen of hearts
print("You drew %s" % card) # You drew Queen of hearts
print([card, Card.new("7", "clubs")]) # [Queen of hearts, 7 of clubs]"You drew " + card is still an error, because + joins two Strings and card is an object. Convert it first: "You drew " + str(card).
A subclass can override _to_string() and use the parent's text with super():
# wild_card.gd
class_name WildCard
extends Card
func _to_string() -> String:
return "Wild " + super()print(WildCard.new("King", "spades")) prints Wild King of spades.
_to_string() returns the text and prints nothing itself. The code that uses the object decides whether the text is printed, joined into a longer line or stored.
Challenge
EasyGive two classes a _to_string() method:
PlayingCardinplaying_card.gdhas arankfrom2to14and asuit. Its text is the rank,ofand the suit, such as7 of clubs. Ranks11,12,13and14are writtenJ,Q,KandA:Q of hearts.Handinhand.gdkeeps its cards in_cards. Its text isHand (N):followed by the cards' texts joined with,, orHand (0): emptywhen it has no cards.
The supplied code prints the empty hand, reads the number of cards, then one RANK SUIT line per card. It adds each card to the hand, prints Drew and the card, and finally prints the hand. For the cards 7 clubs and 12 hearts it prints:
Hand (0): empty
Drew 7 of clubs
Drew Q of hearts
Hand (2): 7 of clubs, Q of heartsYour code goes in playing_card.gd and hand.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 hand := Hand.new()
print(hand)
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
var card := PlayingCard.new(int(parts[0]), parts[1])
hand.add(card)
print("Drew %s" % card)
print(hand)
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