Python __new__ Magic Method – Finxter

0
39
OOP Cheat Sheet Python


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).

OOP Cheat Sheet Python

You can download more cheat sheets here:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



Source link

Leave a reply

Please enter your comment!
Please enter your name here