Python2和Python3的metaclass使用
来源:互联网 发布:企业办公网络优化方案 编辑:程序博客网 时间:2024/05/21 19:40
代码实现通过元类将类对象和实例的属性全部大写。
Python2:
def upper_attr(futer_class_name, future_class_parent, futuer_class_attr): attrs = ((name, value) for name, value in futuer_class_attr.item() if name.startswith('__')) uppercase_attr = dict((name.upper(),value) for name, value in attrs) return type(futer_class_name, future_class_parent, uppercase_attr)__metaclass__ = upper_attrclass Foo(object): bar = 'bip'print(hasattr(Foo, 'bar'))print(hasattr(Foo, 'BAR'))f = Foo()print(hasattr(f,'bar'))print(hasattr(f,'BAR'))
Python 3:
def upper_attr(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) return type(future_class_name, future_class_parents, uppercase_attr)class Foo(metaclass = upper_attr): bar = 'bip'print(hasattr(Foo, 'bar'))print(hasattr(Foo, 'BAR'))f = Foo()print(hasattr(f,'bar'))print(hasattr(f,'BAR'))
Python2 部分代码详细请看深刻理解Python中的元类(metaclass)
阅读全文
0 0
- Python2和Python3的metaclass使用
- 同时使用Python2和Python3
- python3和python2的区别
- python3和python2的区别
- python2和python3的区别
- python2 和Python3的区别
- python2和python3的区别
- python2和python3的区别
- python2和python3的不同点
- Python2和Python3的区别
- python2和python3的区别
- Python2和Python3的比较
- Python2和Python3的print
- Python2和Python3的区别
- python2和python3的区别
- python2和python3的区别
- python2 和 python3 的区别
- Python3 和 Python2的区别
- [源码]跳转MIUI神隐模式列表以及具体设置界面
- 关于linux的vi命令快速记忆方法
- 文章标题
- 静态数据成员
- 《Git 版本控制管理》 学习笔记
- Python2和Python3的metaclass使用
- LeetCode 407. Trapping Rain Water II
- 简单了解"自顶向下,逐步求精"的方法
- 什么是线程?
- 刷题笔记:牛客字符串专项练习4
- Java if条件语句
- 关于Java语言中如何运用反射机制执行某个确定类的构造方法(一)
- 在cocos creator中使用protobufjs(四)
- 线程和进程有什么区别?