Middle
What does the new method do in the context of Python language?
sobes.tech AI
Answer from AI
__new__ is a class method responsible for creating a new instance of the class. It is called before __init__ and determines which object will be returned. It is most often used for creating unique objects (Singleton) or immutable objects (like tuple or str).
class Singleton:
_instance = None
def __new__(cls):
# Check if an instance already exists
if cls._instance is None:
# If not, create it by delegating to the parent class (object)
cls._instance = super().__new__(cls)
# Return the existing or newly created instance
return cls._instance
# Usage examples
s1 = Singleton()
s2 = Singleton()
# Expected result: True
print(s1 is s2)
Comparison of __new__ and __init__:
-
__new__:- Static method (
clsis the first argument). - Called BEFORE the instance is created.
- Returns the created instance.
- Static method (
-
__init__:- Instance method (
selfis the first argument). - Called AFTER the instance is created.
- Does not return a value (implicitly returns None).
- Used for initializing attributes of the created object.
- Instance method (