Four ways to achieve Singleton
First, a static method within a class
IP = '127.0.0.1'
PORT = 3306
class MySQL:
_instance = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
@classmethod
def from_conf(cls):
if not _instance:
cls._instance = cls(IP, PORT)
return cls._instance
Second, the decorative implemented Singleton
def singleton(cls):
cls.__instance = cls(IP, PORT)
def wrapper(*args, **kwargs):
if len(args) == 0 and kwargs == 0:
return cls.__instance
return cls(*args, **kwargs)
@singleton
class MySQL:
def __init__(self, ip, port):
self.ip = ip
self.prot = port
Third, the single-mode embodiment metaclass
class Mymate(type):
def __init__(self, name, bases, dic):
self.__instance = self(IP, PORT)
def __call__(self, *args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
return self.__instance
obj = object.__new__(cls)
obj.__init__(self, *args, **kwargs)
return obj
Four, single-module introduced by way of embodiments
Your own brain supplement the implementation process