============================================= 8: Inside Class ============================================= Summary ============ - __new__ is automatically called to create the instance - __init__ is called after __new__ to add instance attributes to the new instance - __new__ generally works by calling the superclass __new__ to create an instance, but you can use any mechanism that creates an object - As long as the object is of the same type as the class or is subtype the __init__ method is called - One standard example of how __new__ can be used is to create a singleton, a class that can only be initialized once - Another use of __new__ is to customize immutable data objects - Adding a custom __call__ method can be used to convert any object into a callable - This is how class is converted to a callable Program ============ .. literalinclude:: programs/chapterEight.py :language: python Program Output ================= .. code-block:: console (docs-env) root@BMitchellLTOP:~/git/sphinx_students/source/programming_lang/book/programs# python3 chapterEight.py ---- Basic Example ---- __new__ called: Creating instance __init__ called: Initializing instance Name: Brayden ---- Singleton Example ---- Creating new Singleton instance Value: 10 Using existing Singleton instance Value: 20 Are s1 and s2 the same object? True ---- Immutable Customization Example ---- Customizing immutable int Customizing immutable int num1: 5 num2 (negative converted to 0): 0 ---- __call__ Example ---- Calling object like a function: double(5) = 10 double(10) = 20