Python metaclass and pythonmetaclass

Source: Internet
Author: User

Python metaclass and pythonmetaclass

Meta-classes are 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 looks 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 during the class declaration, the _ metaclass _ method is executed. Later, when defining class objects, only the _ init _ () method of the class is called __() method. _ init _ () in MetaClass is executed only once during class declaration.

 

From Python core programming

Recommended: http://www.cnblogs.com/roucheng/p/pythonyunsuan.html

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.