Python meta-class __prepare__ method in-depth understanding

Source: Internet
Author: User
Tags class definition

When learning the meta-class, the __prepare__ is not very understanding, the book is not very detailed explanation, and finally by looking at some of StackOverflow's posts on the method has some understanding, recorded as follows:
Look at the code first:

classMember_table (Dict):def __init__( Self): Self. member_names=[]def __setitem__( Self, key, value):ifKey not inch  Self: Self. Member_names.append (Key)Dict.__setitem__( Self, key, value)classOrderedclass (type):@classmethod    def__prepare__ (METACLS, name, bases): classdict=Member_table ()Print("Prepare return dict ID is:",ID(classdict))returnClassdictdef __new__(Metacls, name, bases, classdict):Print("New Get Dict ID is:",ID(classdict)) Result= type.__new__(Metacls, name, bases,Dict(classdict)) Result.member_names=Classdict.member_namesPrint("The class ' s __dict__ ID is:",ID(result.__dict__))returnResultdef __init__(CLS, name, bases, classdict):Print("Init get dict ID is",ID(classdict))Super().__init__(Name, bases, classdict)classMyClass (Metaclass=Orderedclass):defMETHOD1 ( Self):Pass    defMETHOD2 ( Self):Pass        Print("MyClass locals () ID is",ID(Locals()))

The output is:

returndictidis2093480992528localsidis  2093480992528dictidis2093480992528class‘s __dict__ id is: 2093482830200init get dict id is  2093480992528

Visible, the order of execution is:
Prepare (Create namespace), execute class definition statement, new (Create Class), init (Initialize Class)
After the meta-class defines prepare, it first executes the prepare method, returns an empty custom dictionary, and then executes the class statement, the various attributes defined in the class are collected into a custom dictionary, and finally passed to the new and Init methods.
Another look at the other outputs:

MyClass.member_names
[‘__module__‘, ‘__qualname__‘, ‘method1‘, ‘method2‘]
=‘attr1‘
MyClass.__dict__
mappingproxy({‘__dict__‘: <attribute ‘__dict__‘ of ‘MyClass‘ objects>,              ‘__doc__‘: None,              ‘__module__‘: ‘__main__‘,              ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘MyClass‘ objects>,              ‘attr1‘: ‘attr1‘,              ‘member_names‘: [‘__module__‘,               ‘__qualname__‘,               ‘method1‘,               ‘method2‘],              ‘method1‘: <function __main__.MyClass.method1>,              ‘method2‘: <function __main__.MyClass.method2>})
id(MyClass.__dict__)
2093482829864
MyClass.member_names
[‘__module__‘, ‘__qualname__‘, ‘method1‘, ‘method2‘]

In the above example, in the new method, Dict is replaced with an ordinary dict. So Myclass.member_names does not record the attributes that were added after the class was created. At the same time, the __dict__ property is a proxy for the class namespace, and each view has a different ID.
Prior to version 3.6, the Prepare method was used primarily to return a Orderdict object to hold the order in which the attributes in the class were added. After the 3.6 version, the default is already maintained in order.
Discussion posts on the StackOverflow

Some of the notes you learn are slowly uploading to GitHub, and you are welcome to communicate.
Address is: Https://github.com/telecomshy/python-study

Python meta-class __prepare__ method in-depth understanding

Related Article

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.