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 = unit

We're trying (improperly) to initialize an immutable object.

The following is what happens when we try ...

Get Mastering Object-oriented Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.