How do I subclass without changing the constructor?

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

I have a base class with a custom _init(a, b) function. I have a subclass in which I don’t want to redefine _init. Can I do this? The answer seems to be no:

# in base_class.gd
extends Node

def _init(a, b):
    # etc etc

def some_behavior():
    print("behave")

# in subclass.gd
extends "base_class.gd"

def some_behavior():
    print("misbehave")

# in some other script
var Subclass = preload("subclass.gd")
var sub_instance = Subclass.new("a", "b")
# here I get "Invalid call to function 'new' in base 'GDScript'. Expected 0 arguments."

Edit to add:
To be completely clear about what I am trying to achieve, here is how you would accomplish this in Python:

class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def behave(self):
        print("I am an A. I am " + str(self.a) + str(self.b))

class B(A):
    def behave(self):
        print("I am a B. I am not " + str(self.b) + str(self.a))

a, b = A(1, 2), B(3, 4)
a.behave()  # prints: I am an A. I am 12
b.behave()  # prints: I am a B. I am not 43

The point is that A and B have different behaviors in the behave function, but the object initialization is the same, so there’s no need to rewrite the __init__ function.

But if the subclass has the same _init() then that doesn’t mean it equals its base class? I can’t see what are you trying to achieve.

mateusak | 2016-08-03 23:33

I don’t know of any programming language allowing you to inherit a class and keep the same constructor(s) as the base without writing any, by default you always get a parameter-less constructor. GDScript seem to behave the same, though I don’t see where is the benefit.

Zylann | 2016-08-04 00:00

Thanks mateusak and Zylann for the responses. The subclass isn’t the same–it has different behavior (here indicated by the some_behavior function) but the initialization happens to be the same, so they can use the same constructor.

In fact, you can do this in Python, and since GDScript is based on Python I thought you would be able to do so in GDScript as well. I will update the original question with the Python version, to hopefully clarify what I mean.

Peter O’Malley | 2016-08-04 18:09

I wish someone had answered this. I have this very question bugging my brain right now.

rafgp | 2018-12-26 10:11

:bust_in_silhouette: Reply From: jluini

Just do

# in base class

extends Node

func _init(a, b):
    pass # write constructor here

# in child class

extends "base_class.gd"

func _init(a, b).(a, b):
    pass # nothing here

This is documented here for 3.2: