SoFunction
Updated on 2025-04-11

Detailed explanation of the adaptation and precautions of __new__ method in Python

Preface

newThe () method is a relatively advanced and special constructor in Python that creates and returns new instances of a class.

andinit() The method is different,new() is called before the instance is created, andinit() is called after the instance is created. learnnewThe () method is very important for understanding the creation process of Python objects and implementing certain design patterns (such as singleton pattern, factory pattern, etc.).

Basic usage

newThe () method is a static method, so you need to use the @staticmethod decorator (although in definitionnewdoes not need to do this explicitly because it is considered a static method by default). Its first argument is usually the class itself (customally named cls), followed by other arguments passed to the class constructor.

class MyClass:  
    def __new__(cls, *args, **kwargs):  
        print("Creating a new instance of MyClass")  
        instance = super(MyClass, cls).__new__(cls)  # Call the __new__ method of the parent class to create an instance        return instance  
  
    def __init__(self, value):  
        print("Initializing MyClass instance")  
         = value  
  
# Instantiate MyClassobj = MyClass(10)
Output:

Creating a new instance of MyClass  
Initializing MyClass instance

Return value

newThe () method must return an instance of a class. ifnew() does not return anything (that is, returns None), theninitThe () method will not be called.

class MyClass:  
    def __new__(cls, *args, **kwargs):  
        print("Creating a new instance of MyClass")  
        # Nothing is returned (i.e., it is implicitly returned None)  
    def __init__(self, value):  
        print("Initializing MyClass instance")  
         = value  
  
# Instantiate MyClass, note that __init__ will not be calledobj = MyClass(10)  # Only "Creating a new instance of MyClass" will be output

Singleton mode

newA common use of the () method is to implement a singleton pattern, ensuring that there is only one instance of a class.

class Singleton:  
    _instance = None  
  
    def __new__(cls, *args, **kwargs):  
        if not cls._instance:  
            cls._instance = super(Singleton, cls).__new__(cls)  
        return cls._instance  
  
    def __init__(self, value=None):  
        if not hasattr(self, 'initialized'):  # Make sure __init__ is called only once             = value  
             = True  
  
# Try to create multiple instancesobj1 = Singleton(1)  
obj2 = Singleton(2)  
  
print(obj1 is obj2)  # Output: Trueprint()    # Output: 1, because __init__ will only be called on the first instantiation

Custom object creation

passnew() method, you can customize the object creation process, such as returning different types of objects from factory methods.

class FactoryClass:  
    @staticmethod  
    def __new__(cls, *args, **kwargs):  
        if ('type') == 'A':  
            return ClassA(*args, **kwargs)  
        elif ('type') == 'B':  
            return ClassB(*args, **kwargs)  
        else:  
            raise ValueError("Unknown type")  
  
class ClassA:  
    def __init__(self, value):  
         = value  
        print(f"ClassA instance created with value: {value}")  
  
class ClassB:  
    def __init__(self, value):  
         = value  
        print(f"ClassB instance created with value: {value}")  
  
# Create different types of instances using factory classesobj_a = FactoryClass(type='A', value=10)  
obj_b = FactoryClass(type='B', value=20)

Things to note

Performance considerations:new() is called before the object is created, so it should be executed as quickly as possible.

Inheritance: Used in subclassesnewWhen (), the parent class'snewThe () method to ensure that the object is created correctly.

Immutability: If the class is immutable (such as tuples, strings, etc.), it usually does not need to be rewrited.init(), but may need to be rewritenew() to customize the creation of objects.

Through understandingnew() method allows you to have a deeper understanding of the creation and initialization process of Python objects and design a more flexible and powerful class structure.

Summarize

This is the article about the adaptation and precautions of __new__() method in Python. For more detailed explanations of Python __new__() method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!