
169 views
_new_ in Python
The Python __new__
method is a special method that you can define in a class. It is responsible for creating a new instance of the class. While the __init__
method is used for initializing the attributes of an instance after it has been created, the __new__
method is responsible for the actual creation of the instance.
Here’s a basic example of how you can define and use the __new__
method in a Python class:
Python
class MyClass:
def __new__(cls, *args, **kwargs):
print("Creating a new instance of MyClass")
instance = super().__new__(cls)
return instance
def __init__(self, value):
print("Initializing an instance of MyClass")
self.value = value
# Creating an instance of MyClass
obj = MyClass(42)
In this example:
- The
__new__
method is defined within theMyClass
class. It takes the class itself (cls
) as its first argument, followed by any additional arguments (*args
) and keyword arguments (**kwargs
). It returns a new instance of the class usingsuper().__new__(cls)
. - The
__init__
method is also defined within the class. It initializes thevalue
attribute of the instance. - When an instance of
MyClass
is created (obj = MyClass(42)
), Python first calls the__new__
method to create a new instance, and then it calls the__init__
method to initialize it. - In this example, we’ve added
print
statements to show the order of execution. The__new__
method is called before__init__
, and you can see the output indicating this order.
The use of the __new__
method is relatively rare in typical Python code because most object creation and initialization is handled by the __init__
method. However, there are advanced use cases where customizing __new__
can be beneficial, such as creating immutable objects or implementing singletons.