

python如何实现单例模式?下面给大家带来七种不同的方法:
一:staticmethod
代码如下:
class Singleton(object):
instance = None
def __init__(self):
raise SyntaxError('can not instance, please use get_instance')
def get_instance():
if Singleton.instance is None:
Singleton.instance = object.__new__(Singleton)
return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。
二:classmethod
和方法一类似,代码:
class Singleton(object):
instance = None
def __init__(self):
raise SyntaxError('can not instance, please use get_instance')
def get_instance(cls):
if Singleton.instance is None:
Singleton.instance = object.__new__(Singleton)
return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print('a id=', id(a))
print('b id=', id(b))该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。
三:类属性方法
和方法一类似, 代码:
class Singleton(object):
instance = None
def __init__(self):
raise SyntaxError('can not instance, please use get_instance')
def get_instance():
if Singleton.instance is None:
Singleton.instance = object.__new__(Singleton)
return Singleton.instance
a = Singleton.get_instance()
b = Singleton.get_instance()
print(id(a))
print(id(b))该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。
四:__new__
常见的方法, 代码如下:
class Singleton(object): instance = None def __new__(cls, *args, **kw): if not cls.instance: # cls.instance = object.__new__(cls, *args) cls.instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls.instance a = Singleton() b = Singleton() print(id(a)) print(id(b))
