期望实现单例, 保持某个属性全局唯一
仿照经典实现代码, 却出现了不是单例的情况
实现scheduler全局唯一, 不派生过多的scheduler
拷贝代码
运行之
查看内存地址
仿照经典实现
from apscheduler.schedulers.background import BackgroundScheduler
class Borg(object):
__shared_state = {}
def __init__(self):
self.__dict__ = Borg.__shared_state
self.scheduler = BackgroundScheduler()
s1 = Borg().scheduler
s2 = Borg().scheduler
print s1, s2
# <apscheduler.schedulers.background.BackgroundScheduler object at 0x02623DF0>
# <apscheduler.schedulers.background.BackgroundScheduler object at 0x02D801D0>
我自己想的办法
from apscheduler.schedulers.background import BackgroundScheduler
class Borg(object):
@classmethod
def get_scheduler(cls):
try:
cls_scheduler = cls.scheduler
except AttributeError as e:
cls.scheduler = BackgroundScheduler()
return cls.scheduler
else:
return cls_scheduler
bs1 = Borg.get_scheduler()
bs2 = Borg.get_scheduler()
bs3 = Borg.get_scheduler()
print bs1, bs2, bs3
# <apscheduler.schedulers.background.BackgroundScheduler object at 0x02752D70>
# <apscheduler.schedulers.background.BackgroundScheduler object at 0x02752D70>
# <apscheduler.schedulers.background.BackgroundScheduler object at 0x02752D70>
产品版本: Python 2.7 APScheduler最新
操作系统: Linux
Github链接, 经典实现: https://github.com/faif/pytho...
The classic example is not a pure singleton, but a
Brog
pattern with singleton characteristics.The magic lies in using the dictionary of the class attribute
Create an instance__shared_state
shared by the class. Subsequent instances created will overwrite the__dict__
of the previous instance.Brog
共享的类属性__shared_state
的字典,后面创建的实例会覆盖前面实例的__dict__
In fact, they are two different instances, but their attributes share the same class attributes, which looks like a singleton.
If you change the code to this, you should be able to see the process more clearly:s1
,同时初始化属性scheduler
,此时的地址是0x02623DF0
,再创建一个实例s2
,然后修改了属性scheduler
,地址为0x02D801D0
。s1
和s2