python/公开课/文档/年薪50W+的Python程序员如何写代码/code/Python/opencourse/part01/example08.py
2024-12-04 00:04:56 +08:00

24 lines
427 B
Python

from functools import wraps
from threading import RLock
def singleton(cls):
instances = {}
lock = RLock()
@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]
@singleton
class President:
pass
President = President.__wrapped__