首先创建三个py文件
danli.py
import threading
class Singleton(object):
_lock = threading.Lock()
lit = []
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return Singleton._instance.lit
ceshi.py
from danli import Singleton
def run():
test = Singleton()
test.append(1)
print(test)
test.append(2)
print(test)
ceshi1.py
from danli import Singleton
from ceshi import run
test = Singleton()
run()
test.append(3)
print(test)
执行ceshi1.py结果为:
[1]
[1, 2]
[1, 2, 3]
如有不足,还请多多指正。 参考python中的单例模式实现
|