1. yang xiaoyong
  2. woocode


woocode / py / object / metaclass.py

#!/usr/bin/env python
# -*- encoding:utf-8 -*-


def upper_attr(future_class_name, future_class_parents, future_class_attr):
    """Return a class Object, with the list of its attribute turned
    into uppercase.
    attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
    uppercase_attr = dict((name.upper(), value) for name, value in attrs)

    # let `type` do the class creation
    return type(future_class_name, future_class_parents, uppercase_attr)

# __metaclass__ = upper_attr # this will affect all classes in the module

class Foo(object):
    __metaclass__ = upper_attr
    # we can define __metaclass__ here instead to affect only this class
    bar = 'bip'

print hasattr(Foo, 'bar')
# output: False
print hasattr(Foo, 'BAR')
# output: True

f = Foo()
print f.BAR