python 实现单例模式的四种方法
来源:互联网 发布:mac优酷客户端 编辑:程序博客网 时间:2024/06/03 17:25
1、__new__
class Borg(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): ob = super(Borg, cls) cls._instance = ob.__new__(cls, *args, **kwargs) return cls._instance
class MyClass(Borg): def __init__(self): self.a = 1
if __name__ == '__main__': a1 = MyClass() a2 = MyClass() a1.a = 10 print(a1.a) print(a2.a) print(a1.__dict__)
输出:
1010{'a': 10}
2、共享属性
class Borg2(object): _state = {} def __new__(cls, *args, **kwargs): ob = super(Borg2, cls).__new__(cls, *args, **kwargs) ob.__dict__ = cls._state return ob
class MyClass(Borg2): def __init__(self): self.a = 1
if __name__ == '__main__': a1 = MyClass() a2 = MyClass() a1.a = 10 print(a1.a) print(a2.a) print(a1.__dict__)
输出:
1010{'a': 10}
3、装饰器
def singleton(cls, *args, **kwargs): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance
@singletonclass MyClass(object): def __init__(self): self.a = 1
if __name__ == '__main__': a1 = MyClass() a2 = MyClass() a1.a = 10 print(a1.a) print(a2.a) print(a1.__dict__)
输出:
1010{'a': 10}
4、import方法
# mysingleton .pyclass MyClass(object): def __init__(self): self.a = 1s_myclass = MyClass()
# to usefrom mysingleton import s_myclasss_myclass.a
阅读全文
0 0
- python 实现单例模式的四种方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法:
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- CCF CSP认证考试历年真题 模板生成系统 C语言实现
- 手把手教你将Vim改装成一个IDE编程环境(图文)
- python--map函数
- Validform验证时可以为空,否则按照指定格式验证
- Centos之Git版本管理工具安装-yellowcong
- python 实现单例模式的四种方法
- angular-简单的删除全选demo
- Google分享会
- Nginx expires缓存
- ssh整合时遇到Error creating bean with name 'sessionFactory' defined in class
- [RK3288][Android6.0] 调试笔记 --- hwclock命令无法使用
- plsql12 格式化sql 语句
- Swift UIGestureRecognizer介绍
- MYCAT使用篇(1)