June 2019
Beginner to intermediate
770 pages
19h 24m
English
One use case for the __new__() method is to initialize objects that are otherwise immutable. The __new__() method is where an uninitialized object is created prior to the __init__() method setting the attribute values of the object.
The __new__() method must be overridden to extend an immutable class where the __init__() method isn't used.
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: float, unit: str) -> None: super().__init__(value) self.unit = unit
We're trying (improperly) to initialize an immutable object. Since immutable objects can't have their state changed, the __init__() ...
Read now
Unlock full access