Q12: What is the difference between __new__ and __init__ in Python classes?
__new__(cls, ...): The actual constructor. Allocates and returns a fresh instance of the class in heap memory.__init__(self, ...): The initializer. Takes the instance returned by__new__and configures instance attributes.
Overriding __new__ for Singleton Pattern
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance💡 __new__ controls instance allocation, making it the hook for implementing singletons.
Key Takeaways
__new__creates and returns object instances (used in singletons/immutable subclasses).__init__initializes instance attributes.
Knowledge Check
Which method is executed FIRST when instantiating a Python class instance?