Whenever a superclass implements a __init__ method to initialize its attributes, subclasses derived from it have to invoke the __init__ method of the superclass. This recipe is a different mechanism of initializing the attributes of a superclass with default values, achieved by overriding the __new__ method.
Python, 44 lines
The code shows how to override the __new__ method in order to initialize instance attributes with default values. This may be desirable to ensure that attributes are initialized correctly in subclasses regardless of how the __init__ methods of those subclasses are implemented (e.g., it ensures that the superclasss attributes are initialized before the subclasss attributes). Overriding the __new__ method can be useful also in other cases. This recipe can be seen as a more general mechanism to follow whenever overriding the __new__ method.
Class super1 overrides its __new__ method in order to initialize its attributes with default values. This allows its subclass derived1 to define its own method __init__ without invoking a parent classs __init__ method.
Class super2 is implemented in a similar way, but class derived2 shows how to use such a mechanism in the case of multiple inheritance. Attributes from the superclasses are inherited in this example from left to right, which means that attributes in a superclass can be overridden by attributes in a superclass that succeeds the first one in the inheritance sequence of class derived2. Other implementations can use a different inheritance order by changing the order in the list objList.
One object is created for each superclass, but one of them is chosen to update its own dictionary __dict__ with the entries from all the other objects. Finally, this object is the new object that is returned by the __new__ method.