#单例模式:只产生一次地址
#开发模式:单例模式
class singleleton:
#私有化当前实例(对于内存的优化,保持地址)
#单例的地址就存在于__instance中
__instance=None
name='jack'
#重写__new__
def __new__(cls):
print('__new__')
if cls.__instance is None:
print('是空')
cls.__instance=object.__new__(cls)
print(cls.__instance)
return cls.__instance
else:
print('不是空')
return cls.__instance
def show(self,n):
print('--->show {0} is {1}'.format(self.name,n))
print(dir(singleleton))#查看类中所有的attribute
s=singleleton()
s1=singleleton()
print(s)
print(s1)
s.show(5)
s1.show(7)
输出:
'__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_singleleton__instance', 'name', 'show'
new
是空
<main.singleleton object at 0x000001D38C2F7130>
new
不是空
<main.singleleton object at 0x000001D38C2F7130>
<main.singleleton object at 0x000001D38C2F7130>
--->show jack is 5
--->show jack is 7