Python单例/对象实例化

2024-05-23 17:07:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,我一直在尝试实现一个单例类型的类作为测试。我的代码如下:

_Singleton__instance = None

class Singleton:
    def __init__(self):
        global __instance
        if __instance == None:           
            self.name = "The one"
            __instance = self
        else:
            self = __instance

这在一定程度上起作用,但self=\u实例部分似乎失败了。我已经包含了一些解释程序的输出来演示(上面的代码保存在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__']

有可能做我想做的事吗?如果没有,还有别的办法吗?

欢迎提出任何建议。

干杯。


Tags: theinstance代码nameselfnone类型init
3条回答

赋值给参数或任何其他局部变量(barename)可能永远不会在函数之外产生任何影响;这适用于您的self = whatever,就像它适用于任何其他赋值给(barename)参数或其他局部变量一样。

相反,重写__new__

class Singleton(object):

    __instance = None

    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            cls.__instance.name = "The one"
        return cls.__instance

我在这里做了其他的增强,比如去掉global、旧样式类等

更好的方法是使用Borg(又名monostate)而不是您选择的Highlander(又名singleton),但这与您询问的问题不同;-。

来自Singleton Pattern (Python)

class Singleton(type):
    def __init__(self, name, bases, dict):
        super(Singleton, self).__init__(name, bases, dict)
        self.instance = None

    def __call__(self, *args, **kw):
        if self.instance is None:
            self.instance = super(Singleton, self).__call__(*args, **kw)

        return self.instance

class MyClass(object):
    __metaclass__ = Singleton

print MyClass()
print MyClass()

Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works

class Borg:
  _shared_state = {}
  def __init__(self):
    self.__dict__ = self._shared_state

class MySingleton(Borg):
  def __init__(self, arg):
    Borg.__init__(self)
    self.val = arg
  def __str__(self): return self.val

x = MySingleton('sausage')
print x
y = MySingleton('eggs')
print y
z = MySingleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__. MySingleton instance at 0079EF2C>
<__main__. MySingleton instance at 0079E10C>
<__main__. MySingleton instance at 00798F9C>
'''

相关问题 更多 >