参考了文章:https://www.cnblogs.com/linxiyue/p/3902256.html
http://www.cnblogs.com/liujianzuo888/articles/5561076.html
主要思想是利用类方法或者类属性创建实例,在创建之前做一个判断:
1)使用__new__ 方法
import pymysql
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
charset='utf8')
if __name__ == '__main__':
a = Singleton()
b = Singleton()
print(a.conn, b.conn)
运行输出结果是:
可以看到两个连接都是同一个实例
但是我有疑问,如果实例化要传参,调用__init__初始化的,老是报错,求大神们解答
import pymysql
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class A(Singleton):
def __init__(self, name):
self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
charset='utf8')
self.name = name
if __name__ == '__main__':
apple = A('apple')
banana = A('banana')
Traceback (most recent call last):
File "/Users/daniel/Documents/test/singleton.py", line 19, in
apple = A('apple')
File "/Users/daniel/Documents/test/singleton.py", line 7, in __new__
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
TypeError: object() takes no parameters
另一种是用方法定义
class Singleton(object):
_instance = None
def __init__(self, name):
self.name = name
@classmethod
def get_instance(cls, name):
if cls._instance:
return cls._instance
else:
obj = cls(name)
cls._instance = obj
return obj
if __name__ == '__main__':
_a = Singleton.get_instance('apple')
_b = Singleton.get_instance('banana')
print(_a, _b)
结果如下:
<__main__.Singleton object at 0x10205bd30> <__main__.Singleton object at 0x10205bd30>
总觉得用类方法感觉不够统一,能不能解决__new__创建单例传参的问题呢?可能是py2 和py3的区别吧
参考了文章:
https://docs.lvrui.io/2016/07/03/Python%E5%AE%9E%E7%8E%B0%E7%9A%84%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/
代码如下:
import pymysql
class Singleton(object):
_instance = None
def __new__(cls, name):
if not cls._instance:
cls._instance = object.__new__(cls)
return cls._instance
class A(Singleton):
def __init__(self, name):
self.name = name
self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
charset='utf8')
if __name__ == '__main__':
a = A('apple')
b = A('bnana')
print(a, b)
执行结果:
<__main__.A object at 0x10205bf28> <__main__.A object at 0x10205bf28>