#实现单例
class MyClass():
__isinstance = False
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls.__isinstance :
obj = super().__new__(cls)
cls.__isinstance = obj
return cls.__isinstance
def myenglish(self):
pass
# a = MyClass()
# print(a)
# b = MyClass()
# print(b)
#通过装饰器实现单例
def singleclass(cls):
isinstan = {}
def wrapper(*args,**kwargs):
if not isinstan :
isinstan[cls] = cls(*args,**kwargs)
return isinstan
return wrapper
@singleclass
class MyTest():
pass
m1 = MyTest()
m2 = MyTest()
print(m1,m2)
【单例模式】Python实现单例模式的方式
最新推荐文章于 2024-08-30 12:42:13 发布