Ensure that only one instance of a class gets run(确保只运行类的一个实例)
本文介绍了确保只运行类的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个底层类,我想将其放在一些代码中。我只希望对给定的应用程序实例化或启动一次,尽管它可能会被调用多次。下面代码的问题是LowClass被一遍又一遍地重新启动。我希望每次测试只启动一次。。
import logging
class LowClass:
active = False
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
if self.active:
return
else:
self.active = True
self.log.debug("Now active!")
class A:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
self.lowclass = LowClass()
class B:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
self.lowclass = LowClass()
class C:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
self.a = A()
self.b = B()
class ATests(unittest.TestCase):
def setUp(self):
pass
def testOne(self):
a = A()
b = B()
def testTwo(self):
c = C()
谢谢您指出我的问题!!
推荐答案
请参阅singleton in python。
这篇关于确保只运行类的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:确保只运行类的一个实例
基础教程推荐
猜你喜欢
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
