Metaclass detailed description of Python

Source: Internet
Author: User
A meta class is typically used to create classes. When executing a class definition, the interpreter must know the correct meta-class of the class. The interpreter first looks for the class attribute Metaclass, and if this attribute exists, assigns the attribute to this class as its meta-class. If this property is not defined, it looks up metaclass in the parent class. If the Metaclass attribute is not yet found, the interpreter checks the global variable named Metaclass and uses it as a meta-class if it exists. Otherwise, this class is a traditional class and used types. ClassType as a meta-class of this class.

When the class definition is executed, the correct (typically default) meta-class is checked, and the meta-class (usually) passes three parameters (to the constructor): the class name, the tuple that inherits the data from the base class, and the property Dictionary of the (Class).

When was the meta-class 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)     # What asked Hovertree.comprint ' 4. Class Foo F1 instantiation '  f1=foo ()     print ' 5. Class Foo F2 instantiation '  f2=foo ()     print ' END '  output

Results:

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 in the class declaration, the method in Metaclass is executed, and later when the class object is defined, only the init () method of the class is called, and Init () in Metaclass executes only once at the time of the class declaration.

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.