April 2014
Beginner to intermediate
634 pages
15h 22m
English
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 ...