Python教程:用__new__ 创建单例模式
1.用 __new__
方法
class Singleton(object):
def __new__(cls):
if not hasattr(cls,"_instance"):
cls._instance=super(Singleton,cls).__new__(cls)
# cls.__instance = object.__new__(cls) #这样也可以
return cls._instance
a = Singleton()
b = Singleton()
c = Singleton()
print(a,id(a))
print(b,id(b))
print(c,id(c))
输出:
<__main__.Singleton object at 0x000000000287A240> 42443328
<__main__.Singleton object at 0x000000000287A240> 42443328
<__main__.Singleton object at 0x000000000287A240> 42443328
2.共享属性方法
共享属性:创建实例时把所有实例的__dict__
指向同一个字典,这样它们具有相同的属性和方法.
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob
class MyClass2(Borg):
a = 1
b1 = MyClass2()
b2 = MyClass2()
b3 = MyClass2()
b1.a="萨菲的"
b2.a="萨菲02"
b1.a="萨菲03"
MyClass2.a = 333
print(id(b1),id(b2),id(b3))
print(b1.a,b3.a,b2.a)
print(id(b1.a),id(b2.a),id(b3.a))
输出:
42902024 42902080 42901688
萨菲03 萨菲03 萨菲03
167568080 167568080 167568080
装饰器版本
def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
@singleton
class MyClass:
a = 1
b1 = MyClass()
b2 = MyClass()
b3 = MyClass()
print(id(b1),id(b2),id(b3))
print(b1.a,b3.a,b2.a)
输出:
42712928 42712928 42712928
1 1 1
类方法版
class Foo():
__v = None
@classmethod
def get_instance(cls):
if cls.__v:
print("true: 这是cls.__v",cls.__v)
return cls.__v
else:
print("false: 这是cls.__v", cls.__v)
cls.__v = Foo()
print("false_1: 这是cls.__v", cls.__v)
return cls.__v
obj = Foo.get_instance()
obj1 = Foo.get_instance()
obj2 = Foo.get_instance()
obj3 = Foo.get_instance()
print(obj,"哈哈",id(obj))
print(obj1,"哈哈",id(obj1))
print(obj2,"哈哈",id(obj2))
print(obj3,"哈哈",id(obj3))
输出:
false: 这是cls.__v None
false_1: 这是cls.__v <__main__.Foo object at 0x00000000025002E8>
true: 这是cls.__v <__main__.Foo object at 0x00000000025002E8>
true: 这是cls.__v <__main__.Foo object at 0x00000000025002E8>
true: 这是cls.__v <__main__.Foo object at 0x00000000025002E8>
<__main__.Foo object at 0x00000000025002E8> 哈哈 38798056
<__main__.Foo object at 0x00000000025002E8> 哈哈 38798056
<__main__.Foo object at 0x00000000025002E8> 哈哈 38798056
<__main__.Foo object at 0x00000000025002E8> 哈哈 38798056
单例默认:
"""
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
"""
class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls,"_instance"):
print("你好啊",)
cls._instance = super(Singleton,cls).__new__(cls)
print(cls._instance, "阿斯蒂芬01")
return cls._instance
print( "阿斯蒂芬")
print(cls._instance, "阿斯蒂芬02")
return cls._instance
a = Singleton()
print("这是a",id(a),a)
b = Singleton()
print("这是b",id(b),b)
输出:
你好啊
<__main__.Singleton object at 0x000000000288BEF0> 阿斯蒂芬01
这是a 42516208 <__main__.Singleton object at 0x000000000288BEF0>
阿斯蒂芬
<__main__.Singleton object at 0x000000000288BEF0> 阿斯蒂芬02
这是b 42516208 <__main__.Singleton object at 0x000000000288BEF0>