Metaclasses, static variables, descriptors in Python__ call__ function
編輯:Python
The metaclass
Metaclasses are used to create classes , All except type Other classes are type Created .
type Is a root metaclass , Custom metaclasses mainly override __new__ function , After modifying the class properties, you can return call type Create a modified type .
Functions can also be used as custom metaclasses , Just sign the function and __new__ The same can be , The disadvantage is that you cannot override other metaclass functions .
Static variables
When defining a class ,__init__ The variables in the outer layer of the function are both static variables and instance variables , Variables with the same name have different addresses .__init__ The function is only an instance variable .
When the address of a variable with the same name accessed directly by the class name is different from that accessed by the instance name .
Both variables can be created dynamically , When the class name is dynamically created, two variables are created at the same time , Instance only creates instance variables .
Descriptor
All statements __set__ and __get__ Function types can be used as descriptors
The descriptor instance will call these two functions respectively when assigning or taking values , To achieve numerical verification , Rewriting and other functions .
Function is also a descriptor .
__call__ function
Instances of classes that implement this function can directly call instance(), It can be used as a decorator .