Introduction
In Python, the `__new__` method is a special method that gets called when an instance of a class is created. It is known as the constructor method in Python and is responsible for creating and returning a new instance of the class.
The `__new__` method is called before the `__init__` method, which means it has access to the class attributes and can modify them before the object is initialized. This makes it a powerful tool for metaprogramming and customizing object creation.
One important thing to note about `__new__` is that it always returns an instance of the class. This means that if you override the `__new__` method and don’t return an instance of the class, you’ll get unexpected behavior. Let’s explore how it works in this blog post!
What is __new__?
In Python, `__new__` is a built-in method that is called before the `__init__` method in a class. It is responsible for creating and returning a new instance of the class.
The `__new__` method is static, which means it does not take any reference to the class itself as its first argument like the `__init__` method does. Instead, it takes the class as its first argument followed by any other arguments that are passed to the constructor when creating an instance of the class.
One important thing to note about `__new__` is that it returns an instance of the class. This instance can be either newly created or an already existing one. If `__new__` returns an instance that was created previously, then `__init__` will not be called for that instance.
It is also worth mentioning that if you do not define a `__new__` method in your class, Python will use the default implementation which simply calls `object.__new__(cls)` and returns a new instance of the class.
Overall, understanding how `__new__` works can give you more control over how instances of your classes are created and initialized in Python.
How __new__ works
In Python, the `__new__` method is a special method that is called before an object is created. It is responsible for creating and returning a new instance of a class. The `__new__` method takes in the class as its first argument, followed by any other arguments that are passed to the constructor.
One important thing to note about the `__new__` method is that it is a static method, which means that it does not take in the `self` parameter like other instance methods. Instead, it takes in the class as its first argument and returns a new instance of that class.
Here’s an example of how the `__new__` method works:
class MyClass: def __new__(cls, *args, **kwargs): print("Creating new instance") instance = super().__new__(cls) return instance def __init__(self, *args, **kwargs): print("Initializing instance")my_obj = MyClass()
In this example, when we create an instance of the `MyClass` class, Python calls the `__new__` method first. The `__new__` method simply prints out a message saying that it is creating a new instance, and then it calls the parent class’s `__new__` method to actually create the instance. Finally, it returns the newly created instance.
After the `__new__` method has finished executing, Python calls the `__init__` method to initialize the newly created instance. In this case, the `__init__` method simply prints out a message saying that it is initializing the instance.
When we run this code, we get the following output:
Creating new instance
Initializing instance
As you can see from this example, the `__new__` method allows us to customize how instances of our classes are created. We can use it to perform additional setup or validation before an instance is created, or we can use it to return a previously created instance if necessary.
When to use __new__
The `__new__` method is used as a constructor in Python. It creates and returns a new instance of a class. While the `__init__` method is called after the object is created to initialize its state, the `__new__` method is called before the object is created to create and return the object.
So, when should we use `__new__` instead of `__init__`? The answer lies in the mutability of objects. If an object is mutable, then it can be changed after it has been created. However, if an object is immutable, then it cannot be changed after it has been created.
If we want to create an immutable object, we can use `__new__` to create the object and set its initial state. Since the object is immutable, we don’t need to worry about changing its state later on.
Another use case for `__new__` is when we want to customize how an object is created. By default, calling the class name creates a new instance of that class. However, by defining our own `__new__` method, we can customize how that instance is created.
For example, we could use `__new__` to implement a singleton pattern where only one instance of a class can exist at any given time. We could also use `__new__` to implement a factory pattern where we create different types of objects depending on certain conditions.
In summary, we should use `__new__` when we want to create immutable objects or when we want to customize how an object is created.
Example of using __new__
In Python, the `__new__` method is used to create and return a new instance of a class. It is called before the `__init__` method and is responsible for creating and returning the instance of the class.
Here’s an example of how to use the `__new__` method:
class MyClass: def __new__(cls): print("__new__ method called") instance = super().__new__(cls) return instance def __init__(self): print("__init__ method called")my_object = MyClass()
In this example, we define a simple class `MyClass` with a `__new__` method that prints a message when it is called. We then create an instance of `MyClass` using the usual syntax: `my_object = MyClass()`. When we run this code, we see that the `__new__` method is indeed called before the `__init__` method:
__new__ method called
__init__ method called
Note that in our implementation of `__new__`, we call the superclass’s implementation using `super().__new__(cls)` to actually create the new instance. This is important because it ensures that all necessary initialization is performed by the superclass’s implementation.
Overall, using the `__new__` method can be useful in cases where you need more control over how instances of your class are created. By defining your own `__new__` method, you can customize this process to suit your needs.
Conclusion
In conclusion, the `__new__` method is a powerful tool in Python that allows us to control the creation of new instances of a class. It is responsible for creating and returning new instances of the class, and it is called before the `__init__` method.
By overriding the `__new__` method, we can customize the creation process of new instances. We can return an existing instance instead of creating a new one, or we can create a new instance with different attributes or behavior.
It is important to keep in mind that the `__new__` method is not always necessary, and in many cases, the default implementation provided by Python is sufficient. However, when we need more control over the creation process of new instances, we can use `__new__` to achieve our goals.
In summary, understanding the `__new__` method is crucial for advanced Python programming and for creating custom classes with unique behavior. With this knowledge, we can take our Python skills to the next level and write more efficient, flexible, and elegant code.
Interested in learning more? Check out our Introduction to Python course!

Your FREE Guide to Become a Data Scientist
Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.
Don’t wait, download now and transform your career!
FAQs
What is the constructor in Python __ new __? ›
Python __new__() is the constructor method that controls the creation of the new instance. It is called first and it returns a new class instance. Python __init__() is the initializer method to set the attributes (i.e., state) of the newly-created instance. It is called after creation and returns nothing, i.e., None .
What is the __ new __ function in Python? ›According to the official Python documentation, __new__ is used when you need to control the creation of a new instance while __init__ is used to control the initialization of a new instance.
Can I use new in Python? ›According to the Python documentation, new is used to control the creation of a new instance, whereas init is used to handle its initialization.
What is __ new __ and __ init __ in Python? ›__new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.
What is the difference between __ call __ and __ new __? ›__new__ on the metaclass happens when the class is created, not an instance. __call__ happens when __new__ would happen without the metaclass.
What should __ new __ return in Python? ›__new__ returns a class instance; often referred to as an object, or object instance. It is clearly stated in the docs: The return value of __new__() should be the new object instance (usually an instance of cls ).
Is __ new __ a static method Python? ›__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. As shown above, when __new__() is called directly, the class has to be passed explicitly as the first argument.
What does __ __ mean Python? ›The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.
What does new () do? ›The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.
What is the difference between __ init __ and constructor in Python? ›The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
What is the difference between constructor and method in Python? ›
A constructor helps in initialising an object. A Method is a grouping of instructions that returns a value upon its execution.
What is constructor in Python with example? ›The purpose of a python constructor is to assign values to the data members within the class when an object is initialized. The name of the constructor method is always __init__. In this example, the __init__ method is called when the Person object is created, and it sets the name and age attributes of the object.
What is self and __ init __ method in Python class? ›The python __init__ method is declared within a class and is used to initialize the attributes of an object as soon as the object is formed. While giving the definition for an __init__(self) method, a default parameter, named 'self' is always passed in its argument. This self represents the object of the class itself.
What is Dunder method in Python? ›What are dunder methods? In Python, dunder methods are methods that allow instances of a class to interact with the built-in functions and operators of the language. The word “dunder” comes from “double underscore”, because the names of dunder methods start and end with two underscores, for example __str__ or __add__ .
Why do we use __ init __ file in Python? ›The `__init__.py` file is used to mark a directory as a Python package, making it possible to import modules and sub-packages from that directory. It can also be used to define some initialization code or package-level variables which will be executed when the package is imported.
What makes __ new __ and __ init __ methods different from one another? ›__new__ returns a instance of class. __init__ receives the instances of the class returned by __new__ .
What is the order of __ new __ __ init __ in Python? ›__new__ is the first step of instance creation. It's called first and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.
What are __ methods in Python called? ›Magic methods are special methods in python that have double underscores (dunder) on both sides of the method name. Magic methods are predominantly used for operator overloading.
What does an __ init __ method return? ›The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value.
What type does __ enter __ return? ›__enter__ should return an object that is assigned to the variable after as. By default it is None, and is optional. A common pattern is to return self and keep the functionality required within the same class. __exit__ is called on the original Context Manager object, not the object returned by __enter__ .
What does if __ name __ == __ main __ return in Python? ›
When you run the file as a script by passing the file object to your Python interpreter, the expression __name__ == "__main__" returns True . The code block under if then runs, so Python collects user input and calls echo() .
What is the difference between instance methods and static methods? ›A static method is essentially the opposite of an instance method, since the two cases are mutually exclusive. Instance methods rely on each object's specific data, while static methods must NOT rely on data from a specific object. We call a static method by preceding it with the class name and using dot-notation.
Why not use static methods Python? ›disadvantages of the Python static method
It cannot access attributes or methods of the instance or class. The call signature of a staticmethod is the same as that of a classmethod or instancemethod . This masks the fact that the staticmethod does not actually read or modify any object information.
Static methods can be called without the object of the class. Instance methods require an object of the class. Static methods are associated with the class. Instance methods are associated with the objects.
When to use _ and __ in Python? ›Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).
What is the _ in a variable name in Python? ›Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name. According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation.
What is _ in for loop Python? ›_ can be used in place of a “dummy” variable both in loops and assignment statements where a function returns multiple values, and you want to ignore one or more of them.
What is the function of the constructor? ›A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
What is the difference between operator new and new operator? ›The difference between the two is that operator new just allocates raw memory, nothing else. The new operator starts by using operator new to allocate memory, but then it invokes the constructor for the right type of object, so the result is a real live object created in that memory.
What is the purpose of a constructor and how is it different from other methods? ›Constructors are quite similar to methods, with the key difference being that constructors are invoked whenever an instance of an object is created. Constructors, as opposed to methods, are invoked in order to create and initialise objects that have not yet been created.
Is __ init __ a constructor? ›
"__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts. This method called when an object is created from the class and it allows the class to initialize the attributes of a class.
Do you still need __ init __ in Python? ›There are two types of packages in python, regular and namespace packages. The former requires __init__.py file whereas the latter does not. Any directory with an init python file is marked as a package by python and can be imported.
What are the two types of constructors in Python? ›- Parameterized Constructor.
- Non-parameterized Constructor.
Class constructors are a fundamental part of object-oriented programming in Python. They allow you to create and properly initialize objects of a given class, making those objects ready to use.
What is a real time example of a constructor in Python? ›Real world example
In example, a constructor fo the Car. It sets the default values of variables like number of wheels, number of doors. If you define a class Car, which sets some of the objects variables (note self is used to refer to the objects values), it gets set on creation.
In Python, in order to create and initialize an object of a class, you need a special method and that special method (function) is called constructors. Every class has a constructor, but it is not required to explicitly define it.
How do you access constructor variables in Python? ›- Access inside the constructor by using either self parameter or class name.
- Access class variable inside instance method by using either self of class name.
- Access from outside of class by using either object reference or class name.
The fundamental private method in Python is the __init__() method which is used as a class constructor. This method is called when you initiate the class object depending on the method's argument.
What is __ init __ module in Python? ›The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
What does __ str __ do in Python? ›The __str__() method returns a human-readable, or informal, string representation of an object. This method is called by the built-in print() , str() , and format() functions.
Is __ init __ a magic method? ›
Python Magic Methods. To add "magic" to the class we create, we can define special methods called "magic methods." For example, the magic methods __init__ and __str__are always wrapped by double underscores from both sides.
What is __ doc __ method in Python? ›The __doc__ attribute
Each Python object (functions, classes, variables,...) provides (if programmer has filled it) a short documentation which describes its features. You can access it with commands like print myobject.
From Python documentation: __slots__ allows us to explicitly declare data members (like properties) and deny the creation of __dict__ and __weakref__ (unless explicitly declared in __slots__ or available in a parent.)
Why do you need to add an __ init __ py file when creating a package with some modules? ›If a file named __init__.py is present in a package directory, it is invoked when the package or a module in the package is imported. You can use this to execute package initialization code, for example for the initialization of package-level data.
What is the use of __ file __? ›__FILE__ is a preprocessor macro that expands to full path to the current file. __FILE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.
What is the purpose of the __ Init__ method in a class definition __________? ›The purpose of the __init__ method in a class definition is to. set the instance variable to initial values. A method definition. always must have at least one parameter name, called self.
Is __ init __ a constructor in Python? ›The special method __init__ is the Python constructor. With an understanding of object oriented programming and classes, let's now look at how the __init__ method works within a Python program.
Is Def __ init __ a constructor in Python? ›__init__ "__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts. This method called when an object is created from the class and it allows the class to initialize the attributes of a class.
What is the use of new in constructor? ›The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
Does a constructor create a new object? ›The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
Do you need __ init __ in Python? ›
__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. The __init__ method can be called when an object is created from the class, and access is required to initialize the attributes of the class.
What is the difference between __ construct and init? ›__construct is a php magic method. It always exists and is called on object creation. init() is just a reguar method usually used in ZF..
What is the correct syntax for defining an __ init __? ›The Default __init__ Constructor
The 'self' is a reference object for that class. The syntax for defining a default __init__ constructor is as follows: class class_name(): def __init__(self): # Constructor statements # other class methods … …
Here in __init__() , we define a variable using self. color to indicate that color is instance variable, it belongs to an object. If a class defines an __init__() method, when you create a class instance (an object), Python automatically calls __init__ function only once to initializing an object's variables.
What is the difference between constructor and init method in Python? ›The constructor function in python is called __new__ and __init__ is the initializer function. Quoting the python documentation, __new__ is used when you need to control the creation of a new instance while __init__ is used when you need to control the initialization of a new instance.
Should I use new in a constructor? ›Using new in a constructor violates the D in SOLID (dependency inversion principle). It makes your code hard to test because unit testing is all about isolation; it is hard to isolate class if it has concrete references.
What is the difference between new and constructor? ›The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
Can constructor be called without new? ›No, this is not possible. Constructors that are created using the class keyword can only be constructed with new , if they are [[call]]ed without they always throw a TypeError 1 (and there's not even a way to detect this from the outside).
Are constructors automatically called by new operator? ›A constructor is a special initialization function that is automatically called whenever a class is declared. The constructor always has the same name as the class name, and no data types are defined for the argument list or the return type. Normally a constructor is used to initialize a class.
What is an advantage of using constructor functions to create objects? ›There are the following reasons to use constructors: We use constructors to initialize the object with the default or initial state. The default values for primitives may not be what are you looking for. Another reason to use constructor is that it informs about dependencies.