1
def upper_attr(class_name, class_parents, class_attr): """ 返回一个对象,将属性都改为大写的形式 """ attrs = ((name, value) for name, value in class_attr.items() if not name.startswith('__')) uppercase_attrs = dict((name.upper(), value) for name, value in attrs) return type(class_name, class_parents, uppercase_attrs) # 一种方式: 使用函数赋值给metaclass __metaclass__ = upper_attr pw = upper_attr('Trick', (), {'bar': 0}) print hasattr(pw, 'bar') print hasattr(pw, 'BAR') print pw.BAR # ============================================================== # 另一种方式: 使用赋值给metaclass class UpperAttrMetaClass(type): def __new__(mcs, class_name, class_parents, class_attr): attrs = ((name, value) for name, value in class_attr.items() if not name.startswith('__')) uppercase_attrs = dict((name.upper(), value) for name, value in attrs) return super(UpperAttrMetaClass, mcs).__new__(mcs, class_name, class_parents, uppercase_attrs) class Trick(object): __metaclass__ = UpperAttrMetaClass bar = 12 money = 'unlimited' print Trick.BAR print Trick.MONEY
参考: http://blog.jobbole.com/21351/ http://python.jobbole.com/85126/