Python class method, __ new__ methods and analytical methods __init__

Creating a class in a programming language, a term such configuration method. In Python, we usually think __init__ is the constructor, it is not exactly the same. In constructing the class, a special way __new__ is, this is equivalent to the constructor.

__new__ is a class method, we need to be marked when defining a class method before the function @classmethod decorator, and __new__ do not need to, because it is specially treated. To understand __new__ method, we take a look at what the class method Yes.

Class Methods

class MyClass:

    @classmethod
    def test(cls):
        print(cls.__name__)
        
MyClass.test()
#输出 MyClass

In the MyClass class, test method is a class method, it passed in the first argument for the cls, in fact, MyClass type, print cls .__ name__ can see the results. Class method can be directly 类名.方法名()called. The method is generally based alternative construction method .

The method of application class

>>> from datetime import datetime
>>> datetime.fromtimestamp(324234)
datetime.datetime(1970, 1, 5, 2, 3, 54)

As shown above, the built-in datetime package fromtimestamp is a class method, it can be constructed from a variety of ways datetime objects.

__new__ method

def __new__(cls, a):
    return super().__new__(cls)

__new__ is a class method, so the first parameter is cls, the remaining parameter is the constructor parameters in need. Typically do not need to define __new__ only necessary metaclass programming, it can control the class generation process.
__new__ must return an instance (instance), passed to __init__ method self parameter is an instance variable. Here Returns the parent class (object) of __new__ way to create a new instance. Equivalent to

obj = object.__new__(MyClass)
obj = MyClass()
#obj是实例,上面两个方式等同

Wherein, MyClass is a class, obj is an instance (instance)

__init__ method

__new__ is the constructor, then __init__ is the initialization function, which is responsible for binding to the instance variables, update __dict__ dictionary instance. Wherein the first parameter self is __new__ return value is an instance of the class. __new__ method performed prior to the __init__ method

def __init__(self, a):
    self.a = a

In conjunction with

class MyClass:

    def __new__(cls, a):
        return super().__new__(cls)

    def __init__(self, a):
        self.a = a

obj = MyClass(3)
print(obj.a)

Points

1 .__ new__ is a constructor, __ init__ is the initialization function.
2 .__ new__ manually defined generally not required, is generally used in the metaclass programming, control class generation process.
3 .__ new__ is performed first, and then perform __init__ binding instance variables.
4 .__ new__ must have a return value, the return value is an instance of that class, it will be received __init__ function, commonly called self variable

Guess you like

Origin www.cnblogs.com/PyKK2019/p/11080129.html