Skip to content
Advertisement

Init super with existing instance?

Suppose I have:

JavaScript

How do I correctly initialize the super class with the output of the super class method rather than init?

My OOP background is in C++ and I am continually getting into these scenarios due to the ability to overload constructors in C++, so a workaround for this would be awesome.

Advertisement

Answer

@shx2’s answer works but wastefully/awkwardly creates a throw-away Super object just to initialize the new Regular object with its a attribute.

If you have control over the source of Super, you can make the from_b method create an instance of the given subclass, and have the subclass call the from_b method in its __new__ method instead, so that a Regular object can be both created and initialized directly:

JavaScript

so that the following assertions will pass:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement