Python meta-classes and custom meta-classes

Source: Internet
Author: User

1: Meta-class

Meta class: The creation and management of classes

The meta class of all classes is type

class A:       Pass Print (Type (a))  

Results: <class ' type ' >

2: Custom meta-class

Instantiation of a class: (See the basics and essentials of a Class)

1) Call __new__ () to create an instance

2) call __init__ () to initialize the instance created above

So: Customizing the instance is changing the parent class's __new__ () or __init__ () method

Example:

1 classMymeta (type):2     def __init__(self,name,bases,dicts):3         Print('Init Instance.')4 5     def __new__(cls,name,bases,dicts):6dicts['Info'] =LambdaSelfPrint('DJX.')#Append instance method info ()7res = type.__new__(cls,name,bases,dicts)#invoke the new method of the parent class type to instantiate the instance8Res.company ='Maizi'                       #Append Property9         returnRes#Returning InstancesTen  One classCustom (Metaclass=mymeta):#Use the keyword to indicate that the meta-class is not type but Mymeta A     Pass -  - if __name__=='__main__': thecus =Custom () - Cus.info () -     Print(Cus.company) -  +  - #the writing of python2.x + #class Cus: A  #__metaclass__ = Mymeta at   #Pass

Operation Result:

Init Instance.
Djx.
Maizi

Python meta-classes and custom meta-classes

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.