python两次调用write,单例python调用两次__init__的问题

I have a singleton like this

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)

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??

解决方案

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值