python之metaclass

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__接收到的参数依次是:

  1. 当前准备创建的类的对象;

  2. 类的名字;

  3. 类继承的父类集合;

  4. 类的方法集合。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值