day20-双下new方法,单例模式
# 1. __new__:构造方法,它创造对象,程序员口头语:new一个对象。先执行__new__方法再执行___init__方法。 class Goods: def __init__(self):#如果self后面带有参数,那么下面的cls后面需要加上*args,**kwargs print('init') def __new__(cls):#因为双下new方法创建对象,执行new之前还没有对象,所以这里写cls,不能写self。 print('new') return object.__new__(cls)#借助object类的双下new方法来创建对象,然后返回给上面双下init方法的self。 #这样双下init方法就可以执行了。 g = Goods() print(g.__dict__) # new,先执行双下new方法来创建对象,再执行双下init方法。 # init # {} # 2. 单例模式:一个类只有一个实例化对象。__discount在第一次实例化的时候,等于创建的对象,以后每一次实例化,
都把这个对象返回给self,所以只有一个实例化对象。
class Goods: __discount = False def __init__(self,name): #self接收对象,实例化的时候,self被双下init方法初始化,然后增加name属性。 self.name = name def __new__(cls,*args,**kwargs): if cls.__discount: #为真,说明非空,即有对象。 return cls.__discount #返回给self else: #为假,没对象。 cls.__discount = object.__new__(cls) #增加对象 return cls.__discount #返回给self apple = Goods('apple') print(apple.name) #apple pear = Goods('pear') print(pear.name) #pear,apple和pear这两个变量都是指向同一个实例化对象。 print(apple.name) #pear,apple被pear覆盖了 print(id(apple)) #17656880 print(id(pear)) #17656880,id一样,说明是同一个对象。 apple.color = 'yellow'#apple增加属性 print(pear.color) #yellow print(apple.color) #yellow print(pear._Goods__discount) #<__main__.Goods object at 0x00F86AB0>