The __new__() method and immutable objects
One use case for the __new__() method is to initialize objects that are otherwise immutable. The __new__() method is where our code can build an uninitialized object. This allows processing before the __init__() method is called to set the attribute values of the object.
The __new__() method is used to extend the immutable classes where the __init__() method can't easily be overridden.
The following is a class that does not work. We'll define a version of float that carries around information on units:
class Float_Fail( float ):
def __init__( self, value, unit ):
super().__init__( value )
self.unit = unitWe're trying (improperly) to initialize an immutable object.
The following is what happens when we try to use this class definition:
>>> s2 = Float_Fail( 6.5, "knots" ) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: float() takes at most 1 argument (2 given)
From this, we see...