current position:Home>[untitled] Python magic method__ new__ method

[untitled] Python magic method__ new__ method

2022-02-02 09:47:52 Bayesian grandson

__new__ Construction method :

1. Trigger mechanism : When the object is instantiated

2. effect : Manage the generation process of control objects

3. Parameters : Use one cls To receive the current class , Other parameters are determined according to the instantiated parameters

4. Return value :return not essential no return value , The result of instantiation is None

5. matters needing attention :__new__ Magic method and __init__ The parameters of the magic method are consistent ( Except for the first one )

# __new__  Control generation process of management object 
class Human:
    eye = 2
    skin = 'yello'

    def eat(self):
        print(' having dinner ')

    def drink(self):

    def __new__(cls, sex):
        if sex == 'girl':
            return object.__new__(cls)
        print('__new__ Be triggered ')

xs = Human('boy')

The output is :

  If change to :

xs = Human('girl')

Then the running result becomes :

This indicates that the object was generated , And by the __new__ Controlled . 

copyright notice
author[Bayesian grandson],Please bring the original link to reprint, thank you.

Random recommended