#单例模式:只产生一次地址
#开发模式:单例模式
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