python之metaclass

1python

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/  函數

相關文章
相關標籤/搜索