python3如何使用元类
来源:互联网 发布:影音后期制作软件大全 编辑:程序博客网 时间:2024/05/05 15:25
在python2中可以通过定义一个类级别属性__metaclass__来实创建元类,不过在python3中取消了__metaclass__属性。python3中可以通过在定义类的时候声明metaclass参数来创建元类。
实例1:增加一个__author__类属性
class Author(type): def __new__(cls, name, bases, attrs): attrs['__author__'] = 'xiemanR' return type.__new__(cls, name, bases, attrs)class MyBlog(metaclass=Author): passprint(MyBlog.__author__)a = MyBlog()print(a.__author__)
实例2:使用元类创建单例模式
class Singleton(type): def __new__(cls, name, bases, attrs): print('new') attrs['instance'] = None return super(Singleton, cls).__new__(cls, name, bases, attrs) def __call__(cls, *args, **kwargs): print('call') if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instanceclass Foo(metaclass=Singleton): passx = Foo()y = Foo()print(id(x))print(id(y))
实例3:将类属性转化为大写的形式
class Upper(type): def __new__(cls, name, bases, dct): attrs = ((name, value) for name, value in dct.items() if not name.startswith('__')) uppercase_attr = dict((name.upper(), value) for name, value in attrs) return type.__new__(cls, name, bases, uppercase_attr)class Bar(metaclass=Upper): foo = 'foo' test = 'test'b = Bar()print(b.FOO)print(b.TEST)
阅读全文
0 0
- python3如何使用元类
- Python3之元类
- python3学习笔记:元类metaclass
- Python3中的PyMongo如何使用?
- Python3元组
- Python3元组
- Python3基础-元组
- python010 Python3 元组
- 【Python】Python3 元组
- Python3 元组
- Python3 元组
- 如何使用Python3.4连接MySQL
- 如何使用Python3读写INI配置文件
- 如何使用Python3.4连接MySQL
- Python3的解析库BeautifulSoup如何使用?
- Python使用元类
- python 使用元类
- 使用元类
- 从汇编角度看待数组名和指针
- NYoj 263 精 挑 细 选
- 第二十四课_遍历windows对象目录
- mysql中游标的使用案例详解(学习笔记)
- Html5斜45度地图+3D模型ARPG系列教程(3)-- 关于如何运行示例项目
- python3如何使用元类
- 只包含因子2 3 5的数
- squid的正反向代理
- Linux运维笔记-文档总结-mariadb数据库的各项操作(全)
- Linux--RH254---unit 8 mariadb数据库
- MATLAB面向对象编程命名空间的使用
- 二叉树遍历
- ASP.NET HttpModule的使用说明
- C和指针 练习 1-3