Python meta-class __metaclass__

Source: Internet
Author: User

<pre name= "code" class= "Python" > #python元类, the class creation process # First calls type.__new__# and then calls the class's constructor class.__init__def toString (c): s    =""; If Type (c) ==tuple:s= "tuple:" For I in C:s+=str (i) s+= "," Return s elif Typ E (c) = = dict:s= "dict:" For K,v in C.items (): s+= "k=%s,v=%s"% (k,v) s+= "," re    Turn S elif type (c) = = list:s= "list:" For I in C:s+=str (i) s+ "," return s Else:return C class Listmetaclass (type): Def __new__ (CLS, name, bases, attr): #对于比较长的代码行, you can use \  Come to the branch #有没有感觉跟C + + define definition of line-breaking feel the same (-><*><-) print (' cls=%s, name=%s,bases=%s,attrs=%s '%        (ToString (CLS), ToString (name), ToString (bases), ToString (attr)))     attr[' Add ']=lambda self,value:self.append (value) return type.__new__ (CLS, name, bases, attr) class MyList (list): __metaclass__ = Listmetaclass If __name__ = = "__main__": MyList = MyList () mylist.add (+) print (myList) def listadd (self,value): Self.appe nd (value) MyList2 = Listmetaclass ("MyList2", (list,), Dict (Add=listadd)) Mylist2=mylist2 () Mylist2.add (10 XX) print (MYLIST2) "" "Program output: Cls=<class ' __main__. Listmetaclass ', Name=mylist,bases=tuple:<type ' list ' >,,attrs=dict:k=__module__,v=__main__,k=__ Metaclass__,v=<class ' __main__. Listmetaclass ' >,[100]cls=<class ' __main__. Listmetaclass ', Name=mylist2,bases=tuple:<type ' list ' >,,attrs=dict:k=add,v=<function listAdd at     0X01AACBB0&GT;,[1000] "" "


Python meta-class __metaclass__

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.