Python is an Object oriented programming language i.e everything in Python is an object. There are special kind of methods in Python known as magic methods or dunder methods (dunder here means “Double Underscores”). Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. These are commonly used for operator overloading.
Few examples for magic methods are:
Note: To know more about Magic methods click here.
Whenever a class is instantiated
__init__methods are called.
__new__method will be called when an object is created and
__init__method will be called to initialize the object. In the base class
object, the __new__ method is defined as a static method which requires to pass a parameter
clsrepresents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.
class class_name: def __new__(cls, *args, **kwargs): statements . . return super(class_name, cls).__new__(cls, *args, **kwargs)
Note: Instance can be created inside
__new__ method either by using
super function or by directly calling
__new__ method over object, where if parent class is object. That is
instance = super(MyClass, cls).__new__(cls, *args, **kwargs) or
instance = object.__new__(cls, *args, **kwargs)
If both __init__ method and __new__ method exists in the class, then the __new__ method is executed first and decides whether to use __init__ method or not, because other class constructors can be called by __new__ method or it can simply return other objects as an instance of this class.
Creating instance Init is called
The above example shows that __new__ method is called automatically when calling the class name, whereas __init__ method is called every time an instance of the class is returned by __new__ method, passing the returned instance to __init__ as the
self parameter, therefore even if you were to save the instance somewhere globally/statically and return it every time from __new__, then __init__ will be called every time you do just that.
This means that if the super is omitted for __new__ method the __init__ method will not be executed. Let’s see if that is the case.
Creating instance None
In the above example, it can be seen that __init__ method is not called and the instantiation is evaluated to be
None because the constructor is not returning anything. Let’s see what happens if both the __new__ and __init__ methods are returning something.
Creating instance GeeksforGeeks Initializing instance
Traceback (most recent call last): File "/home/62216eb30d3856048eff916fb8d4c32d.py", line 17, in
print(B()) TypeError: __init__() should return None, not 'str'
This TypeError is raised by the handler that calls __init__ method and it wouldn’t even make sense to return anything from __init__ method since it’s purpose is just to alter the fresh state of the newly created instance.
Let’s try an example in which __new__ method returns an instance of a different class.
- Python – The new generation Language
- Zip function in Python to change to a new character set
- Python | Return new list on element insertion
- Python | Add new keys to a dictionary
- Python PIL | Image.new() method
- rangev2 - A new version of Python range class
- Open a new Window with a button in Python-Tkinter
- How to create a new thread in Python
- Using mkvirtualenv to create new Virtual Environment - Python
- How to Filter and save the data as new files in Excel with Python Pandas?
- Connect new point to the previous point on a image with a straight line in Opencv-Python
- What's new in Python 3.9?
- Python VLC Instance - Creating new Media Instance
- Awesome New Features in Python 3.8
- Add a new column in Pandas Data Frame Using a Dictionary
- Adding new column to existing DataFrame in Pandas
- Create a new column in Pandas DataFrame based on the existing columns
- PyQt5 - How to hide ComboBox when new item get selected
- New '=' Operator in Python3.8 f-string
- Insert a new axis within a NumPy array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.