Metaclass for python

Source: Internet
Author: User
This article describes metaclass in details about python. metaclass is generally used to create classes. When executing the class definition, the interpreter must know the correct metadata of the class. The interpreter first looks for the class property metaclass. if this property exists, it is assigned to this class as its meta class. If this attribute is not defined, it will look up metaclass in the parent class. if the metaclass attribute is not found, the interpreter checks the global variable named metaclass. if it exists, it is used as a metaclass. Otherwise, this class is a traditional class and uses types. ClassType as its metadata class.

When defining an execution class, the correct (usually the default) meta class will be checked. the meta class (usually) will pass three parameters (to the constructor): class name, inherit the data tuples from the base class and the (class) attribute Dictionary.

When will the metadata be created?

#! /Usr/bin/env python print '1. metaclass declaration 'class Meta (type): def init (cls, name, bases, attrd): super (Meta, cls ). init (name, bases, attrd) print '3. create class % R' % (name) print '2. class Foo declaration 'class Foo (object): metaclass = Meta def init (self): print '*. init class % R' % (self. class. name) # Question hovertree. comprint '4. class Foo f1 instantiation 'F1 = Foo () print '5. class Foo f2 instantiation 'F2 = Foo () print 'end' output

Result:

1. Metaclass declaration

2. Class Foo declaration

3. Create class 'foo'

4. Class Foo f1 instantiation

*. Init class 'foo'

5. Class Foo f2 instantiation

*. Init class 'foo'

END

It can be seen that the metaclass method is executed when the class object is declared. when defining the class object, only the init () method of the class is called, and the init () method in MetaClass () it is executed only once during class declaration.

The above is a detailed description of python metaclass. For more information, see other related articles in the first PHP community!

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.