SoFunction
Updated on 2024-11-12

Python __new__ built-in static method use analysis

This article introduces the python __new__ built-in static methods used to analyze the text through the sample code is very detailed, for everyone's learning or work has a certain reference learning value, the need for friends can refer to the next!

When you create an object using class name(), the python interpreter calls the __new__ method to allocate space for the object. __new__ is a built-in static method provided by the object base class that serves two main purposes:

(1) Allocating space in memory for objects

(2) Returning a reference to an object

The python interpreter, after obtaining a reference to an object, passes the reference as the first argument to the __intit__ method.

The code for rewriting the __new__ method is very fixed: rewriting the __new__ method must return super(). __new__(cls), otherwise the python interpreter won't get a reference to the object with space allocated and won't call the object's initialization method.

class MusicPlayer:
  def __new__(cls, *args, **kwargs):
    print("Create object, allocate space.")

  def __init__(self):
    print("Player initialization")
player = MusicPlayer()
print(player)

Output:

Need to return return super(). __new__(cls)

All python classes have a base class object, and the default __new__ method in object already encapsulates the action of allocating space for an object.

class MusicPlayer(object):
  def __new__(cls, *args, **kwargs):
    print("Create object, allocate space.")
    instance = super().__new__(cls)
    return instance

  def __init__(self):
    print("Player initialization")
player = MusicPlayer()
print(player)

Output:

This is the whole content of this article, I hope it will help you to learn more.