Meta-class Metaclass
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 a constructor that passes 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 and a warning if no __repr__ () method is provided.
The from warnings import warn# meta class needs to inherit the type class Class reqstrsugrepr (type): def __init__ (CLS, NAME, BASES, ATTRD): #构造函数需要传递的参数为类名, base class, Class Property dictionary super (REQSTRSUGREPR, CLS). __init__ (NAME, BASES, ATTRD # determine if the __str__ string is in the class's 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): #给类指定元类 __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.
Resources:
http://blog.jobbole.com/67748/
Http://www.cnblogs.com/btchenguang/archive/2012/08/27/2659369.html
http://blog.csdn.net/dysj4099/article/details/18862137
Meta-class Metaclass in Python