单例python调用两次__init__的问题 [英] issue with singleton python call two times __init__

查看:257
本文介绍了单例python调用两次__init__的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的单身汉

class Singleton:

    class __impl:
        def __init__(self):
            print "INIT"

    __instance = None

    def __init__(self):
        # Check whether we already have an instance
        if Singleton.__instance is None:
            Singleton.__instance = Singleton.__impl()

        # Store instance reference as the only member in the handle
        self.__dict__['_Singleton__instance'] = Singleton.__instance

    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)

当我创建多个Singleton实例时,有两次调用 init ,我的意思是"INIT"被打印两次,并且我认为它不应该发生

When I made several instances of Singleton I get two calls to init , I mean "INIT" is printed two times, and I supose that it shouldn't happened

有人对这个问题有什么想法,或者有更好的方法来实现呢?

Somebody has an idea of what is wrong with this or has a better way to implement this??

推荐答案

这是一种编写Singleton的简单方法:

Here's a slightly simpler way to write a Singleton:

class Singleton(object):
    __instance = None
    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = super(Singleton,cls).__new__(cls)
            cls.__instance.__initialized = False
        return cls.__instance

    def __init__(self):      
        if(self.__initialized): return
        self.__initialized = True
        print ("INIT")

a = Singleton()
b = Singleton()
print (a is b)

尽管可能有更好的方法.我必须承认,我从不喜欢单身人士.我更喜欢工厂类型的方法:

although there may be better ways. I have to admit that I've never been fond of singletons. I much prefer a factory type approach:

class Foo(object):
    pass

def foo_singleton_factory(_singlton = Foo()):
    return _singleton

a = foo_singleton_factory()
b = foo_singleton_factory()
print (a is b)

这样做的好处是,如果需要,您可以继续获取Foo的相同实例,但是如果您决定在未来10年内不想使用真正的单例,则不仅限于单个实例.

This has the advantage that you can keep getting the same instance of Foo if you want it, but you're not limited to a single instance if you decide 10 years down the road that you don't want a true singleton.

这篇关于单例python调用两次__init__的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆