Creation and use of Metaclass meta-classes in Python

Source: Internet
Author: User
In Python we use the type function to dynamically create a meta-class, as well as to use the __metaclass__ property to specify a meta-class, and then we will give a concrete example of the creation and use of the Metaclass meta-class in Python

A meta-class is a way for you to define how certain classes are created. Fundamentally, gives you control over how to create classes.
A meta-class is also a class, which is a type class.

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, and if this property is not defined, it will look up the __metaclass__ property in the parent class. If you haven't found it yet, look for global variables.

For traditional classes, their meta-class is types. ClassType.

The Meta class also has constructors that pass three parameters: the class name, the tuple that inherits the data from the base class, and the Class property dictionary.
Let's define a meta class that requires the class to be provided with a __str__ () method, if no __repr__ () method is provided,
You'll be warned.

The From warnings import warn# class needs to inherit type class Reqstrsugrepr (type):  def __init__ (CLS, name, bases, ATTRD):  # The constructor needs to pass the arguments to the class name, the base class, and the Class Property dictionary    Super (REQSTRSUGREPR, CLS). __INIT__ (name, bases, ATTRD)    # Determine if the __str__ string is in the class's Property dictionary    if ' __str__ ' not in ATTRD:      raise TypeError (' Class requires overriding of __str__ () ')    if ' __repr__ ' isn't in ATT RD:      warn (' Class suggests overriding of __repr__ () \ n ', stacklevel=3) Class Foo (object):  #给类指定元类   __ metaclass__ = Reqstrsugrepr  def foo (self):    pass# This piece of code does not need to create a class to test, run directly will be error, visible meta-class skill.


The type function can see the types of a variable, such as:

# <type ' int ' ># <type ' str ' >type (1)     type (' mink ')

The type function can also create a new object
Type accepts three parameters, name, bases, Dict first accepts class name, second parameter accepts parent class (tuple form), third parameter accepts property and method (dictionary form)

x = Type (' x ', (object,), Dict (a=1)) # equals class X (object):  a = 1

Here's how to accept a function

Def say (self):  print ' hello ' x = Type (' x ', (object,), Dict (Say=say)) x = x () # pirnt Hellox.say ()

Meta class

We all know that a class can create an instance object, whereas a meta-class is a class that creates a class object. Type can create a class object, which means that the type is a meta-class.

Metaclass Property

If you want to create a class object using a meta-class, you need to add a __metaclass__ property to the object. Of course, you have to have a meta-class first.

Class Privatemetaclass (Type):  def __new__ (CLS, name, parents, attrs):    attrs = Dict ((' __%s '% K, v) for K, V in ATT Rs.itmes ())    return Super (Privatemetaclass, CLS). __new__ (CLS, name, parents, Attrs) class A (object):  __ metaclass__ = Privatemetaclass  a = 1  b = 2a = A () # Raise Attributeerrorprint a.a, a.b # print 1, 2print a.__a, a._ _b

This allows you to modify some of the properties of the class by using a meta class, which is to modify the variable to be a private variable.

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: 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.