A meta-class is a class class that enables us to customize classes, that is, we define classes by class, essentially meta-classes, which are templates for classes.
Four Step walk:
One: The process of controlling class definition classes
1. Get the class name first
2. After getting the base class
3. Execute the class code to get the dict of the namespace
4. Call the meta-class to pass three parameters in
#其实class is the four-step package above. (Isolation of complexity)
Two: Custom meta-classes
Class Mymeta (Type):
def __init__ (self,class_name,class_base,class_dic):
Super (). __init__ (Class_name,class_base,class_dic)
Class My (Object,metaclass=mymeta):
Pass
Three: Control classes and the generation of objects
class Bar:
def __call__ (self, *args, **kwargs):
Print (self)
print (args)
P Rint (Kwargs)
Bar = bar ()
Bar (' Test ') #对象后面加括号触发
Class Mymeta (Type):
def __init__ (self, class_name, Class_base, Class_dic):
‘‘‘
:p Aram Class_name: Class name
:p Aram Class_base: base class
:p Aram Class_dic: namespaces
‘‘‘
If not Class_name.istitle ():
Raise ValueError (' class name needs to be case ')
If Class_dic.get (' __doc__ '):
Content = Class_dic.get (' __doc__ ')
Content = Content.replace (",")
Content = Content.replace (' \ n ', ')
If Len (content) ==0:
Raise ValueError (' class cannot have no comment ')
If ' __doc__ ' not in class_dic or not clas_dic.get (' __doc__ '). Strip ():
Raise TypeError (' must specify a document comment for the class ')
Super (Mymeta, self). __new__ (Class_name, class_name, Class_dic)
Class Mysql:
‘‘‘
‘‘‘
def __init__ (self, Host, Port):
Self. Host = Host
Self. Port = Port
#创建类的两种方式
Way one:,
Using the class keyword
class people (object):
Def talk (self):
Print (' Hello ')
def walk (self):
Print (' Walk ')
Way two:
The process of manually simulating class creation classes: Splitting the steps to create a class, manually creating,
Three conditions are required to create a manual
Need to get it separately
1. Class name
2. The parent class of the class
3. Class body (Dict of namespaces after execution)
Class_name=people
Class_base=object
Class_body= ' #类体
Def talk (self):
Print (' Hello ')
def walk (self):
Print (' Walk ')
‘‘‘
cla=2wss_dic={}
Step one (dealing with the namespace): The name of the class body definition is stored in the namespace of the class (a local namespace), we can define an empty dictionary beforehand, and then use exec to execute the class body code
(exec produces namespaces similar to the real class process, except that the latter will deform the attributes that begin with _, generating the local namespace of the class, which is the fill dictionary)
EXEC (Class_body,globals,class_dic)
Step Two:
People=type (Class_name,class_base,class_dic)
#实例化type得到对象Foo, that is, we get the object people, that is, the class we define with class people
A meta class that does not appear to declare itself, and the default inheritance is type
88
The meta-class of Python object-oriented programming