Ai
1 Star 0 Fork 2

open/Python-100-Days

forked from 阿甘/Python-100-Days 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example10.py 938 Bytes
一键复制 编辑 原始数据 按行查看 历史
jackfrued 提交于 2019-02-13 07:38 +08:00 . 更新了文档和目录结构
"""
装饰类的装饰器 - 单例模式 - 一个类只能创建出唯一的对象
上下文语法:
__enter__ / __exit__
"""
import threading
from functools import wraps
def singleton(cls):
"""单例装饰器"""
instances = {}
lock = threading.Lock()
@wraps(cls)
def wrapper(*args, **kwargs):
if cls not in instances:
with lock:
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class President():
def __init__(self, name, country):
self.name = name
self.country = country
def __str__(self):
return f'{self.country}: {self.name}'
def main():
print(President.__name__)
p1 = President('特朗普', '美国')
p2 = President('奥巴马', '美国')
print(p1 == p2)
print(p1)
print(p2)
if __name__ == '__main__':
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
HTML
1
https://gitee.com/netb/Python-100-Days.git
git@gitee.com:netb/Python-100-Days.git
netb
Python-100-Days
Python-100-Days
master

搜索帮助