Python __new__
In Python, __new__
is a special method that is automatically called before the __init__
method when creating a new instance of a class. It is responsible for creating and returning a new instance of the class.
Here is an example to demonstrate the usage of __new__
:
class MyClass:
def __new__(cls, *args, **kwargs):
print("Creating a new instance")
instance = super().__new__(cls) # Creating a new instance using the superclass __new__ method
return instance
def __init__(self, name):
print("Initializing instance")
self.name = name
obj = MyClass("Example")
In this example, the __new__
method is defined in the MyClass
class. It prints a message indicating that a new instance is being created and uses the super()
function to call the __new__
method of the superclass. Finally, it returns the newly created instance.
After __new__
finishes, the __init__
method is called. It prints a message indicating that the instance is being initialized and sets the name
attribute of the instance.
When running this example, you will see the following output:
Creating a new instance
Initializing instance
This shows that the __new__
method is called before the __init__
method and is responsible for creating the new instance.