附源码:
class SingletonObject(object):
class __SingletonObject():
def __init__(self):
print ('init')
self.val=None
def __str__(self):
# print ('str' )
return "{0!r} {}".format(self,self.val)
instance = None
def __new__(cls):
if not SingletonObject.instance:
print( 'set')
SingletonObject.instance = SingletonObject.__SingletonObject()
print ('s')
return SingletonObject.instance
def __getattr__(self, item):
print ('hello')
return getattr(self.instance, item)
def __setattr__(self, key,value):
print ('get')
return setattr(self.instance, value)
obj1 = SingletonObject()
obj1.val = 'value 1'
print("*"*22)
print("print obj1:",obj1)
obj2 = SingletonObject()
obj2.val = 'value 2'
print(obj1)
print(obj2)
print(obj1.val)
错误:
改: