Curriculum
In Python, __new__ is a special method that is responsible for creating and returning a new instance of a class. It is called before __init__ and is used to create an instance of the class. The __new__ method is used when you want to create a new object of a class.
Here’s an example of how __new__ can be used in Python:
class Person:
def __new__(cls, name, age):
print("Creating new person")
instance = super().__new__(cls)
instance.name = name
instance.age = age
return instance
def __init__(self, name, age):
print("Initializing person")
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name)
print(person.age)
In this example, we define a class Person with __new__ and __init__ methods. In the __new__ method, we create a new instance of the Person class by calling the super().__new__(cls) method, which returns a new instance of the class. We then set the name and age attributes of the instance and return it.
In the __init__ method, we initialize the name and age attributes again. When we create an instance of the Person class, __new__ is called first, followed by __init__. The output of the above code will be:
Creating new person Initializing person Alice 25
As you can see, the __new__ method is called first, and then the __init__ method is called. The __new__ method is responsible for creating a new instance of the class, while the __init__ method is responsible for initializing the instance with the given parameters.