#单例模式class Dog(object): #定义一个类变量 #None相当于c++中的NULL,修饰基本类型和类类型均可 instance = None #重写__new__方法 def __new__(cls): if None == cls.instance: #调用父类__new__方法创建对象 cls.instance = object.__new__(cls) return cls.instance else: return cls.instanced1 = Dog()print(id(d1))d2 = Dog()print(id(d2))#结果显示两个对象的地址相同
#单例模式--特殊赋值class Cat(object): instance = None #python要求__new__方法的参数必须和__init__方法的参数一致,虽然在__new__方法中只有cls这个形参有用 def __new__(cls,name): if None == cls.instance: cls.instance = object.__new__(cls) return cls.instance else: return cls.instance def __init__(self,name): self.name = namec1 = Cat("tom")print(id(c1))print(c1.name)#打印tomc2 = Cat("jack")print(id(c2))print(c2.name)#打印jack#这是因为__init__方法并没有做instance的判断,所以d2的调用相当于重新给name赋值了
#单例模式--完成版class Cat(object): instance = None initFlag = True def __new__(cls,name): if None == cls.instance: cls.instance = object.__new__(cls) return cls.instance else: return cls.instance def __init__(self,name): #保证__init__只执行一次 #注意类变量的调用方式 if Cat.initFlag: self.name = name Cat.initFlag = Falsec1 = Cat("tom")print(id(c1))print(c1.name)#打印tomc2 = Cat("jack")print(id(c2))print(c2.name)#打印tom