The class in Python calls the __new__ () class method to create an instance, calls the __init__ () method to initialize the object, and the object's destruction calls the __del__ () method.
The __new__ () method is the first parameter of the class CLS, typically returning an instance of the CLS, and then the new instance of the __init__ () method will be similar to __init__ (self[, ...]) The way is called, Self is the new instance created, the other parameters are the same as those passed to __new__ ().
If the __new__ () method does not return an instance of the CLS, then __init__ () will not be called.
For a class:
Class Foo (object): def __init__ (self, name): self.name = NAMEF = Foo (' Bar ')
When you do an F = Foo (' bar ') operation, you actually perform the following steps to create and initialize the instance:
f = foo.__new__ (foo, ' Bar ') if Isinstance (F, foo): foo.__init__ (F, ' Bar ')
__new__ (cls[, ...])
The __new__ () method is a static class method that takes the class of the instance as the first parameter. The remaining arguments are arguments passed to the object construction expression, as is passed to __init__ ().
Typically by using super (Currentclass, CLS). __new__ (cls[, ...]) To call the __new__ () method of the superclass to create a new instance of the class.
The __new__ () method is rarely defined when a user customizes an object. If defined, it is usually when you define a meta-class or define some objects that inherit from immutable built-in data types (integers, strings, tuples, and so on).
When defining some immutable data types, because the object is immutable, the object cannot be modified in __init__ (), and the __new__ () method is executed before the instance is created:
Class Upperstr (str): def __new__ (CLS, value= "): return str.__new__ (CLS, Value.upper ())
The string instances created by the Upperstr class above are all capitalized:
>>> u = upperstr (' Hello World ') >>> u ' Hello World '
You can also use the __new__ () method in singleton mode to create a unique instance, put it in a class variable, and return this instance each time you create it:
Class Singleton (object): def __new__ (CLS, *args, **kwargs): If not hasattr (CLS, ' _inst '): cls._inst=super (Singleton, CLS). __new__ (CLS, *args, **kwargs) return Cls._inst
__init__ (self[, ...])
The __init__ () method is used to initialize the properties of the object, which is called when the instance creation is complete. Parameters are those parameters that are passed to the class constructor expression. If the base class has the __init__ () method, then the inherited class's __init__ () method, and must be explicitly called: baseclass.__init__ (self, [args ...]).
A special limitation of the constructor is that no value can be returned, and doing so will cause the runtime to throw a typeerror.
The __init__ () method generally contains a large number of self.attr = attr Assignment Statements:
Class Foo (object): def __init__ (self, name, color, num=1): self.name = name Self.color = Color self.num = NUMF = Foo (' Bar ', ' yellow ')
If you do not want to repeat this assignment, there are several options:
Class Foo (object): def __init__ (self, name, color, num=1): print locals () f = Foo (' Bar ', ' yellow ')
The local namespace for the __init__ () method is as follows:
{' Color ': ' Yellow ', ' self ': <__main__. Foo object at 0x00000000055c4780>, ' num ': 1, ' name ': ' Bar '}
The self variable is the created instance itself, and the rest of the variable Name,color,num to assign a value to the instance is in it. The instance properties are stored in the __dict__ variable of the instance, and we just need to put the variables to be assigned to the __dict__:
Class Foo (object): def __init__ (self, name, color, num=1): self.__dict__.update (Locals ()) del self.__ dict__[' self ']
>>> f = Foo (' Bar ', ' yellow ') >>> f.name ' bar ' >>> f.color ' yellow ' >>> f.num1
This is a lot more concise when the instance properties are many. However, when you use attributes or descriptors to wrap an object's properties, the problem arises because attributes or descriptor wrapper properties are not stored in __dict__, and the solution is to use setattr built-in functions:
def attr_from_locals (locals_dict): Self = Locals_dict.pop ("self") for k,v in Locals_dict.items (): SetAttr (self, k, v) class Foo (object): def __init__ (self, name, color, num=1): attr_from_locals (Locals ())
If the __init__ () method uses some local variables that are not assigned to the instance, then using locals () will include these local variables, and we can pass the parameters in the __init__ () precisely.
The F.__code__ property of a function f can get the byte code object C of the function, the byte code object's attribute C.co_varnames can get the tuple of the local variable name (function parameter before, local variable inside function), c.co_ Argcount can get the number of function position parameters, using slices can remove local variables in function:
def attr_from_locals (locals_dict): Self = Locals_dict.pop ("self") code = self.__init__.__func__.__code__ args = Code.co_varnames[1:code.co_argcount] for K in args: setattr (self, k, locals_dict[k]) class Foo (object): def __init__ (self, name, color, num=1): x = 1 attr_from_locals (Locals ()) F = Foo (' Bar ', ' Yellow ')
You can see that the x variable is not assigned to the instance:
>>> f.name ' bar ' >>> f.color ' yellow ' >>> f.num1>>> f.xtraceback (most recent call Last): File "<pyshell#87>", line 1, in <module> f.xattributeerror: ' Foo ' object have no attribute ' x '
__del__ (self)
The __del__ () method of the object is called when the instance is to be destroyed. Note that when using a statement such as Del A, the __del__ () method is not called, only a reference count is reduced, and __del__ () is called when the object's reference count is reduced to 0 o'clock.
The __del__ () method is rarely necessary to define an instance of this method and cannot be collected by the Python recycle garbage collector.
When a purge operation is required (close the file, close the network connection, and so on), it is a better idea to define a close () method to explicitly perform the shutdown operation.
Object behavior and special method (i) object creation and destruction in Python