python中最好理解的实现单例模式的方法

实现单例模式,及python程序在调用某一个类的时候,永远只出现一个实例(可以节约内存,CPU):

1,通过包的形式写在外面以import的形式导入,最直接。

2,以__new__方法创建单例模式,代码如下:

class Singleton(object):
def __init__(self):
pass
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance: # 每次调用前检查有没有_instance属性,没有就通过父类的__new__创建
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)# 每一个类都自带__new__方法,在__init__之前用__new__实例化,将结果传给self.
return cls._instance

class MyClass(Singleton):
  pass
one=MyClass()
two=MyClass()
print(id(one))
print(id(two))
#>>id(one)==id(two)

 

posted @ 2020-04-15 17:49  阿木木的木  阅读(197)  评论(0编辑  收藏  举报