class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kwargs)
return cls._instance
class MyClass(Singleton):
a = 1
one = MyClass()
two = MyClass()
#one和two完全相同,可以用id(), ==, is检测
print id(one) # 29097904
print id(two) # 29097904
print one == two # True
print one is two # True
class Singleton2(type):
def __init__(cls, name, bases, dict):
super(Singleton2, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Singleton2, cls).__call__(*args, **kwargs)
return cls._instance
class MyClass2(object):
__metaclass__ = Singleton2
a = 1
one = MyClass2()
two = MyClass2()
print id(one) # 31495472
print id(two) # 31495472
print one == two # True
print one is two # True
def singleton(cls, *args, **kwargs):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class MyClass3(object):
a = 1
one = MyClass3()
two = MyClass3()
print id(one) # 29660784
print id(two) # 29660784
print one == two # True
print one is two # True
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有