几年前,我在Duncan Booth的 Python中找到了Singleton模式的实现:
class Singleton(object):
"""
Singleton class by Duncan Booth.
Multiple object variables refers to the same object.
http://web.archive.org/web/20090619190842/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#singleton-and-the-borg
"""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
Run Code Online (Sandbox Code Playgroud)
问题还描述了" 在Python中定义单例的简单,优雅的方法吗? "
我通过子类别使用Singleton:
class Settings(Singleton)
class Debug(Singleton)
最近我对程序做了一些修改并得到了这个警告:
/media/KINGSTON/Sumid/src/miscutil.py:39: DeprecationWarning:
object.__new__() takes no parameters
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
我找到了关于弃用的解释(由Guido 解释),__new__其中说参数根本没有使用.传递不需要的参数可能是错误的症状.
所以我决定清除参数:
class Singleton(object):
_instance = None
def __new__(cls):
if not cls._instance: …Run Code Online (Sandbox Code Playgroud) 我正在学习Python,并且我一直在尝试将Singleton类型的类作为测试.我的代码如下:
_Singleton__instance = None
class Singleton:
def __init__(self):
global __instance
if __instance == None:
self.name = "The one"
__instance = self
else:
self = __instance
Run Code Online (Sandbox Code Playgroud)
这部分工作,但self = __instance部分似乎失败了.我已经包含了解释器的一些输出来演示(上面的代码保存在singleton.py中):
>>> import singleton
>>> x = singleton.Singleton()
>>> x.name
'The one'
>>> singleton._Singleton__instance.name
'The one'
>>> y = singleton.Singleton()
>>> y.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Singleton instance has no attribute 'name'
>>> type(y)
<type 'instance'>
>>> dir(y)
['__doc__', '__init__', '__module__']
Run Code Online (Sandbox Code Playgroud)
有可能做我正在尝试的事情吗?如果不是,还有另一种方法吗?
欢迎任何建议.
干杯.
我有一个基础类,我想放在一些代码中.我只希望它被实例化或为给定的应用程序启动一次,虽然它可能被多次调用..下面代码的问题是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 = …Run Code Online (Sandbox Code Playgroud)