Source

woocode / py / object / metaclass-2.py

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

# upperattr_metaclass: 一个方法总是接收当期实例作为第一个参数传入
# 就跟原来方法传入 `self` 一样

class UpperAttrMetaclass(type):
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attr):
        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)
        # we call `type` directly and we don't override call the parent
        # `__new__`

        return type.__new__(upperattr_metaclass,
                            future_class_name,
                            future_class_parents, uppercase_attr)


class Foo:
    __metaclass__ = UpperAttrMetaclass
    def foo(self):
        print 'Upper'

f = Foo()
f.FOO()