metaclasses are what create these objects.They are the classes' classes.
http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
type
type is the metaclass Python uses to create all classes behind the scenes.
age = 35
age.__class__
#<type 'int'>
age.__class__.__class__
#<type 'type'></span>
自定义metaclass
The main purpose of a metaclass is to change the class automatically, when it's created. You usually do this for APIs, where you want to create classes matching the current context. A typical example of this is the Django ORM.
当用户定义一个类时,Python解释器首先在当前类的定义中查找__metaclass__,如果没有找到,就继续在父类中查找,找到了,就使用父类中定义的__metaclass__来创建,也就是说,metaclass可以隐式地继承到子类,但子类自己却感觉不到。
class UpperAttrMetaclass(type):
# __new__ is the method called before __init__
# it's the method that creates the object and returns it
# while __init__ just initializes the object passed as parameter
# you rarely use __new__, except when you want to control how the objectis created.
# here the created object is the class, and we want to customize it, so we override __new__
# you can do some stuff in __init__ too if you wish
# some advanced use involves overriding __call__ as well
def __new__(cls, clsname, bases, dct):
uppercase_attr = {}
for name, val in dct.items():
if not name.startswith('__'):
uppercase_attr[name.upper()] = val
else:
uppercase_attr[name] = val
return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr)
__new__接收到的参数依次是:
-
当前准备创建的类的对象;
-
类的名字;
-
类继承的父类集合;
-
类的方法集合。