classMetaClass(type): def__new__(self, name, bases, attr): attrs = ((name, value) for name, value in attr.items() ifnot name.startswith('__')) uppercase_attr = dict((name.upper(), value) for name, value in attrs) defsay_hello(cls): print'hello guys!' t = type.__new__(self, name, bases, uppercase_attr) t.say_hello = say_hello return t classMetaTest(object): __metaclass__ = MetaClass bar = 'attrs' object_1 = MetaTest() object_1.say_hello() print object_1.BAR print object_1.bar
运行测试结果:
1 2 3 4 5 6 7
hello guys! attrs
Traceback (most recent call last): File "E:\Study\PythonPractice\meta_two.py", line 18, in <module> print object_1.bar AttributeError: 'MetaTest' object has no attribute 'bar'