object.__new__(cls[, ...])
Python’s __new__(cls)
magic method creates a new instance of class cls
. The remaining arguments are passed to the object constructor. The return value is the newly-created object—an instance of cls
.
Basic Example
The following example shows how each time you create an object of our custom class My_Class
, Python calls the __new__()
magic method.
class My_Class(object): def __new__(cls): print("Python is great!") return super(My_Class, cls).__new__(cls) My_Class()
Output:
Python is great!
The expression super(My_Class, cls).__new__(cls)
is a standard approach to use the super()
built-in function to call the __new__()
method of the parent class.
Feel free to watch our related video on super()
to gain an additional understanding:
Python __new__ vs __init__
Python __new__()
creates and returns a new instance whereas __init__()
initializes the state of an instance.
- 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
.
You can see that __new__()
is called before __init__()
in the following code example:
class My_Class(object): def __new__(cls): print("Python is great!") return super(My_Class, cls).__new__(cls) def __init__(self): print("Finxter42") My_Class()
Output:
Python is great! Finxter42
Feel free to watch our explainer video on the related method __init__()
here:
We used some important terms of object-oriented programming in Python to explain our examples. Make sure to study the following cheat sheet (you can also download the PDF here).
Click the image to get the cheat sheet (opens in a new tab).
You can download more cheat sheets here:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.