Godot equivalent of overwriting "to_string" for print output

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tybobobo
:warning: Old Version Published before Godot 3 was released.

In many other languages you can overwrite an to_string() func/method that is used to set the output when you directly attempt to print the classvar.

For example;

var calendar = preload("../../Calendar.gd").new()
print(calendar)

Output should be todays datetime, such as “15-09-16”
However it is something like [Node:500]. Is there a way to make the print(calendar) output “15-09-16”?

I suggest you create a get_date_string() method instead. I would expect this kind of output on a Date object, not a Calendar, but it’s my personal opinion :stuck_out_tongue:
You could even have get_date() outputting a dictionary with day, month and year, then str() would work out of the box on it.

Zylann | 2016-09-15 18:15

:bust_in_silhouette: Reply From: supaiku

Not yet. See here magic _str method by profelis · Pull Request #6306 · godotengine/godot · GitHub

Glad to see that I am not the only one wanting this :slight_smile:

Tybobobo | 2016-09-15 12:49

:bust_in_silhouette: Reply From: Hammer Bro.

Yet! As of May 23, 2019 https://github.com/godotengine/godot/pull/27886 was merged, adding the _to_string() virtual method to Object.

It behaves exactly as you’d expect, though at present you may have to get/make a custom build to have access to that patch.

Hooray! And it only took about three years! :smiley:

Ertain | 2019-08-06 00:14