"__init__()" and "__new__()": Sequence and Purpose
"__init__()" and "__new__()" are fundamental methods in Python's object-oriented programming used to control instance creation and initialization.
"__new__()" is responsible for allocating memory and creating a new instance of a class, returning the newly created object. It is responsible for the actual creation of an instance.
In contrast, "__init__()" initializes the newly created instance. It is responsible for setting up the instance's attributes and performing any necessary actions to prepare the object for use.
Python's design dictates that "__init__()" is always called after "__new__()" in the instance creation process. This is because the new instance needs to be initialized after it has been created.
Flyweight Pattern and "__init__()" Invocation
In the context of the Flyweight pattern, you may be confused about the expected behavior of "__init__()" being called after "__new__()". This is because the Flyweight pattern typically utilizes "__new__()" to control instance creation and avoid creating multiple copies of the same object.
In your example code, you have implemented a custom "__new__()" method to handle instance creation based on the existence of a key in a dictionary. However, you may have intended for the "__init__()" method to be called only once, even for subsequent instances created using the Flyweight pattern.
Why is "__init__()" Always Called After "__new__()"?
The reason for this behavior is that Python's object-oriented system expects every instance created to be initialized through the call to "__init__()". This is a fundamental part of the instance creation process, ensuring that the object is fully prepared for use.
Alternative Implementation
To implement the Flyweight pattern and avoid calling "__init__()" multiple times, you should use a factory class instead of overriding "__new__()". This is considered a more robust and standard approach.
Here's an example of a factory-based Flyweight implementation:
class FlyweightFactory: _cache = {} def __get(key): if key not in FlyweightFactory._cache: FlyweightFactory._cache[key] = Flyweight(key) return FlyweightFactory._cache[key] class Flyweight: def __init__(self, key): self.key = key
In this implementation, the factory class creates and caches instances based on a key, avoiding the need for multiple "__init__()" calls.
The above is the detailed content of Why is `__init__()` Always Called After `__new__()` in Python's Object Creation?. For more information, please follow other related articles on the PHP Chinese website!