由于我们都忽略了您的问题,而是提出了替代的单例实现,所以我会提出我最喜欢的。它利用了一个python模块只加载一次的事实,无论你导入多少次。
它也基于蟒蛇的座右铭“我们在这里都是成年人”,因为如果你真的想要,你可以多次实例化它......但是你真的必须付出额外的努力才能做错。
所以在mysingleton.py
:
class SingletonClass(object):
def __init__(self):
# There's absolutely nothing special about this class
# Nothing to see here, move along
pass
# Defying PEP8 by capitalizing name
# This is to point out that this instance is a Singleton
Singleton = SingletonClass()
# Make it a little bit harder to use this module the wrong way
del SingletonClass
然后像这样使用它:
from mysingleton import Singleton
# Use it!
我说你必须付出额外的努力才能做错事。以下是如何创建单例类的两个实例,使其不再是单例:
another_instance = Singleton.__class__()
那么如何避免这个问题呢?我会引用医生的话:那就不要那样做!
注意:这是在做出以下评论后添加的
当我在这里时,这里有另一个单例变体,它可以最大限度地减少复杂代码的数量。它使用元类:
class SingletonMeta(type):
# All singleton methods go in the metaclass
def a_method(cls):
return cls.attribute
# Special methods work too!
def __contains__(cls, item):
return item in cls.a_list
class Singleton(object):
__metaclass__ = SingletonMeta
attribute = "All attributes are class attributes"
# Just put initialization code directly into the class
a_list = []
for i in range(0, 100, 3):
a_list.append(i)
print Singleton.a_method()
print 3 in Singleton
在 python 3 中,您将创建这样的单例实例:
class Singleton(metaclass=SingletonMeta):
attribute = "One... two... five!"
Now this one is a little more iffy, since the singleton is a class, and you can make instances of the singleton. In theory this is OK, since the singleton will still be a singleton even if it has instances, but you need to remember that Singleton()
is not the singleton -- Singleton
is! It might even suit your needs to have the singleton attributes readily available to its instances as class attributes.