Call time

To create a class object, the new method is called to generate an instance of the object, followed by an automatic (implicit) callback to the init method.

Why do WE need a new method?

The init method, executed after instantiation, controls the initialization of the value of the private address space. The new method is executed before instantiation and controls the process of class instantiation. Some properties cannot be changed after class instantiation and can only be changed during instantiation. Not only manipulate properties, but even change the output to return arbitrary class instances.

How does the new method change properties?

scenario

If a subclass inherits immutable types such as int, STR, or tuple, it can change its attributes using the new method

The principle of

The characteristic of immutable types is that after instantiation, properties cannot be changed. For example, if a = 10, the new phase creates an address block in memory to store the value of 10, which cannot be changed later. Therefore, the custom assignment logic should be performed in the new method.

implementation

class PositiveInteger(int) :
    Construct an integer type that is always positive.
    def __new__(cls, value, *args, **kwargs) :
        The # new method opens the memory space where the value of value is stored. It is not allowed to change the value of this space later
        return super(PositiveInteger, cls).__new__(cls, abs(value), *args, **kwargs)
Copy the code

How does the new method change the class instance returned?

scenario

Just to name a few:

  • Singleton pattern (the concept will not be repeated, understand everything)
  • The Book class is used to create objects, which are automatically classified into SportBook, ScienceBook, and ArtBook based on the type and number of parameters

implementation

class GlobalMaster(object) :
    Construct a singleton class property instance that holds the instantiated object of the class. The distinction between class properties and object properties is not repeated here.
    instance = None

    def __new__(cls, *args, **kwargs) :
        if not cls.instance:
            cls.instance = super(GlobalMaster, cls).__new__(cls)
        Instantiation of a class always returns the same object as long as it is running in the same process space
        return cls.instance


class Book(object) :
    """ Construct a book class instantiation master entry, return different book class object according to the argument in the example omitted SportBook class creation, are ordinary 'CLSS SportBook:' written. After 'a = Book("sport")', methods like a.ent () and a.turn () call SportBook's methods instead of Book's. "" "
    def __new__(cls, value, *args, **kwargs) :
        if value == "sport":
            return super(Book, cls).__new__(SportBook)
        elif value == "science":
            return super(Book, cls).__new__(ScienceBook)
        elif value == "art":
            return super(Book, cls).__new__(ArtBook)
        else:
            raise ValueError(F "Unknown types of books:{value}")
Copy the code

Refer to the link

  • Explain __init__ and __new__ in Python