day-20 双下new方法,单例模式

#  1. __new__:构造方法,它创造对象,程序员口头语:new一个对象。
class Goods:
    def __init__(self):
        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
                  # init
                  # {}

# 2. 单例模式:一个类只有一个实例化对象。
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
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>

猜你喜欢

转载自www.cnblogs.com/python-daxiong/p/11255140.html
今日推荐