Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | patatra |
Hye everyone,
Can a class created in a class_name have a constructor?
Good Day,
Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | patatra |
Hye everyone,
Can a class created in a class_name have a constructor?
Good Day,
Reply From: | cm |
Yes, you can override _init
.
See Class constructor in the docs
It’s work, thank you
Good Day,
patatra | 2022-05-14 08:36
You can use the named constructor pattern. E.g.
class_name MyClass extends Node
var parameter: int
static func create(new_params: int) -> MyClass:
var instance = MyClass.new()
instance.parameters = params
return instance
Then create your instances like MyClass.create(...)
instead of MyClass.new()
.
Why do you reply to a question 2 years later, with a solution that isn’t wrong but just unnecessary? (You can override _init() with parameters already, no need for your own create() method.)
Because searching for constructors in Godot I ended up here. I didn’t like the solution becase it is not really a contructor and I shared an alternative solution in case it is usefull for others.
When using _init signature hinting is just on-editor validated and it just suggests the number or arguments. Also it lacks semantic.
I believe that named constructor is a more robust approach.
IMHO it’s not a more robust method because now you have two methods to create the object, which makes it more prone for bugs.
It is not a matter of discussion, Named Constructors/Factory Methods is a well known design pattern.
If it fits your needs, you use it.
As I said, it is also a matter of semantic. In your projects reality it may happen instantiating an object is not the same as “creating” it.
If you have some kind of persistence, it is not the same creating an object with default values, than recovering them form a resource. For instance.
Create method in this case acts as boilerplate state generator.