后续慢慢补充
简单总结一句,实例对象由类对象实例化产生,那么类对象由什么产生呢?那就是元类 。简单理解为 元类的实例化是类对象, 类对象的实例化是 实例对象 。
demo1
zhangji16@zhangji16vm:~/c_study/hw_idarling/support_prj$ cat metaclass2.py
#!/usr/bin/env python
# coding=utf-8
class UpperAttrMetaclass(type):
def __new__(cls, clsname, bases, attrs):
uppercase_attrs = {}
for name, val in attrs.items():
if not name.startswith('__'):
uppercase_attrs[name.upper()] = val
else:
uppercase_attrs[name] = val
print(UpperAttrMetaclass)
return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attrs)
print "here"
class Foo(object):
__metaclass__ = UpperAttrMetaclass
def zj(self):
pass
运行一下这个程序
zhangji16@zhangji16vm:~/c_study/hw_idarling/support_prj$ python -i metaclass2.py
here
<class '__main__.UpperAttrMetaclass'>
>>> f = Foo()
>>> f
<__main__.Foo object at 0x7fdd8dc05250>
>>> f.zj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'zj'
>>> f.ZJ
<bound method Foo.zj of <__main__.Foo object at 0x7fdd8dc05250>>
>>> f.ZJ()
Foo 类的属性被修改了,也就是用 大写的名字才能访问的到 相应的属性。
所以元类属性的作用自然是:
- 拦截类的生成
- 修改类
- 返回修改后的类