The new method in Python is a fundamental method that is responsible for creating instances of a class. It is often referred to as a "static" method, although technically it's a class method because Python implicitly passes the class (cls) as the first argument.
The primary role of __ new __ is to create and return a new instance of a class. It is called before __ init __, which initializes the created instance. Here’s a step-by-step breakdown:
-
Class Creation: When we write a class and create an instance of it, Python internally calls
__ new __to create the object. -
Instance Initialization: After
__ new __creates the instance, Python then calls__ init __to initialize it.
class MyClass:
def __new__(cls, *args, **kwargs):
# Custom object creation logic goes here
instance = super().__new__(cls)
# Additional initialization can be done here if needed
return instance
def __init__(self, *args, **kwargs):
# Instance initialization code goes here
pass
# Creating an instance of MyClass
obj = MyClass()
-
__ new __Method:- Parameters:
__ new __accepts the class (cls) as the first parameter, followed by any additional arguments (*args) and keyword arguments (**kwargs). - Customization: we can override
__ new __to customize how instances of our class are created. This could involve creating the instance using a different method or adding additional attributes. - Return Value:
__ new __should return an instance of the class (cls). Typically, we create the instance usingsuper().__ new __(cls)to invoke the parent class's__ new __method.
- Parameters:
-
__ init __Method:- Initialization:
__ init __initializes the instance after it has been created by__ new __. It's where we typically set up initial attributes and perform any other initialization tasks.
- Initialization:
Let's say we have a class Person where we want to ensure that every person's name is capitalized when the instance is created:
class Person:
def __new__(cls, name):
# Ensure name is capitalized
capitalized_name = name.capitalize()
instance = super().__new__(cls)
instance.name = capitalized_name
return instance
def __init__(self, name):
# Initialization can be done here, if needed
pass
# Creating instances
person1 = Person("Wajed")
person2 = Person("Tintin")
print(person1.name) # Output: Wajed
print(person2.name) # Output: Tintin
-
Control over Instance Creation:
__ new __provides control over how instances are created. This is useful for customizing object creation logic or enforcing constraints. -
Static/Class Method: Even though it's commonly referred to as static due to its usage pattern, technically it's a class method because Python passes the class (cls) implicitly.
-
Usage: While
__ init __is where we typically initialize instance attributes,__ new __allows for more advanced customization of instance creation, making it powerful for handling special cases or enforcing specific behaviors during object instantiation.