Create and use metaclass in Python

Source: Internet
Author: User
In Python, we can use the type function to dynamically create a metaclass, or use the _ metaclass _ attribute to specify a metaclass, next we will give an example to illustrate how to create and use metaclass in Python. in Python, we can use the type function to dynamically create a metaclass, you can also use the _ metaclass _ attribute to specify a metaclass. next we will illustrate how to create and use metaclass in Python.

Meta-classes allow you to define how some classes are created. Fundamentally, it gives you control over how to create a class.
A metadatabase is also a type class.

Meta-classes are generally used to create classes. When executing the class definition, the interpreter must know the correct metaclass of the class. if this property is not defined, it will look up the _ metaclass _ attribute in the parent class. If no global variable is found, search for the global variable.

For traditional classes, their Meta classes are types. ClassType.

The Metadatabase also has a constructor that transmits three parameters: class name, data tuples inherited from the base class, and class attribute Dictionary.
Next we will define a metadata class. we need to provide a _ str _ () method for the class when writing the class. if The _ repr _ () method is not provided,
Then you are warned.

From warnings import warn # the metaclass must inherit the type class ReqStrSugRepr (type): def _ init _ (cls, name, bases, attrd ): # The parameters to be passed by the constructor are class name, base class, and class attribute dictionary super (ReqStrSugRepr, cls ). _ init _ (name, bases, attrd) # judge whether the _ str _ string is in the class attribute dictionary if '_ str _' not in attrd: raise TypeError ('class requires overriding of _ str _ () ') if' _ repr _ 'not in attrd: warn ('class suggests overriding of _ repr _ () \ n', stacklevel = 3) Class Foo (object) : # Specify metaclass _ = ReqStrSugRepr def foo (self) for the class: pass # this code does not need to create a class for testing. if you run it directly, an error is returned, you can see the power of the meta class.

Type

The type function can view the type of a variable, for example:

# 
 
  # 
  
   type(1)     type('mink')
  
 

The type function can also create a new object.
Type accepts three parameters: name, bases, and dict. The first parameter accepts the class name, the second parameter accepts the parent class (in the form of tuples), and the third parameter accepts the attributes and methods (in the dictionary form)

X = type ('X', (object,), dict (a = 1) # equals to class X (object): a = 1

The following describes how to accept functions.

def say(self):  print 'hello'X = type('X', (object,), dict(say=say))x = X()# pirnt hellox.say()

Metadata

We all know that instance objects can be created through classes, and meta classes are the classes used to create class objects. Type can be used to create a class object, that is, type is a Metaclass.

Metaclass attributes

To create a class object using a metaclass, add the _ metaclass _ attribute to the object. Of course, you must first have a metadata class.

class PrivateMetaclass(type):  def __new__(cls, name, parents, attrs):    attrs = dict(('__%s' % k, v) for k, v in attrs.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

In this way, you can modify some features of the class through the meta class. the above is to change the variable to a private variable.

For more information about how to create and use metaclass in Python, see PHP!

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.