什么是单例模式:
单例模式即一个类有且仅有一个实例
class Mysql:
__instance = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
@classmethod
def from_conf(cls):
if cls.__instance is None:
cls.__instance = cls("127.0.0.0", 8888)
return cls.__instance
# 单例模式
obj1 = Mysql.from_conf()
obj2 = Mysql.from_conf()
obj3 = Mysql.from_conf()
print(obj1)
print(id(obj1))
print(obj2)
print(id(obj2))
print(obj3)
print(id(obj3)) # obj1、obj2、obj3的id一样,为一个实例
# 不单例
print("*"*50)
obj4 = Mysql("127.0.0.0", 9999)
print(obj4)
print(id(obj4)) # obj4的id改变,不是单例
<__main__.Mysql object at 0x10ea9cfa0>
4540977056
<__main__.Mysql object at 0x10ea9cfa0>
4540977056
<__main__.Mysql object at 0x10ea9cfa0>
4540977056
**************************************************
<__main__.Mysql object at 0x10ea9cee0>
4540976864
Process finished with exit code 0
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/tech/python/278082.html