First, the execution process of creating the class
The understanding of the meta-class
What is a meta-class? The meta-class that inherits type in Python3
Examples of meta-classes
# Way One Class MyType (type): ' Inherits type ' is Meta class ' Def __init__ (Self,*args,**kwargs) : Print ("MyType created object", self) #Foo super (mytype,self). __init__ (*args,**kwargs) def __call__ (self, *args, **kwargs): obj = Super (mytype,self). __call__ (*args,**kwargs) print ("Class Creation Object", Self,obj) #Fooclass Foo (object, Metaclass=mytype): # object parentheses will execute the __call__ method, __call__ method inherits the Type __call__ method, type of the __call_ _ Method inside will execute __new__ method first, then go to execute __init__ method. So, Foo is created with type user = "Haiyan" age = 18obj = Foo ()
# Way Two Class MyType (type): Def __init__ (self, *args, **kwargs): Print ("SSSs ") Super (MyType, self). __init__ (*args, **kwargs) def __call__ (CLS, *args, **kwargs): v = Dir (CLS) obj = Super (MyType, CLS). __call__ (*args, **kwargs) return obj# object parentheses will execute __call__ method class Foo (MyType (' Zcc '), (object,) , {})): #MyType (' Zcc ', (object,), {}) is equivalent to class ZCC (object):p, that is, creating a Zcc class user = ' Haiyan ' age = 18obj = Foo ()
# Way Three Class MyType (type): def __init__ (self, *args, **kwargs): print ("SSSs") super (MyType, self). __init__ (*args, **kwargs) Def __call__ (CLS, *args, **kwargs): v = dir (cls) obj = Super (MyType, CLS). __call__ (*args, **kwargs) return Obj# object parentheses will execute __call__ method def with_metaclass (arg,base): print ("Class object", MyType (' Zcc ', (base,), {})) return arg (' ZCC ', (base,), {}) #返回一个类对象 <class ' __main__. ZCC ' >class Foo (With_metaclass (Mytype,object)): #MyType (' Zcc ', (object,), {}) equals class Zcc (object):p That is to create a ZCC class user = ' Haiyan ' age = 18obj = Foo ()
Additional
Class ASD (type): PASSQQQ = ASD ("Qwe", (object,), {}) #用ASD这个元类创建了一个 (Qwe, and inherits the object class of) Classes # class ASD (qwe): # Passobj = QQQ () # can create a class is a meta-class # can be created object is class print (obj) #<__main__.qwe object at 0x00000000024ffba8>print (obj.__class __) #<class ' __main__.qwe ' >print (obj.__class__.__class__) #<class ' __main__. ASD ' >print (obj.__class__.__class__.__class__) #<class ' type ' >print (obj.__class__.__class__.__class __.__class__) #<class ' type ' >
Python Full stack Development Foundation "supplemental" Metaclass (Meta Class)