1.创建一个类
1 class danli: 2 __obj =None
2.重写new方法
def __new__(cls,*args,**kwargs):if cls.__obj is None: #判断当前类对象的类属性为空cls.__obj = object.__new__(cls) #当前类属性为空 则调用父类object的new方法创建新对象return cls.__obj
3.防止初始化__init__ 多次调用
class danli:__obj = None__init_flag = True
def __init__(self,name)if danli.__init_flag: #标记,防止函数多次初始化self.name = namedanli.__init_flag =False
4.验证是否只生成一个对象
1 class danli: 2 __obj = None 3 __init_flag = True 4 5 def __new__(cls,*args.**kwargs): 6 if cls.__obj is None: 7 cls.__obj = object.__new__(cls) 8 return cls.__obj 9 10 def __init__(self.name): 11 if danli.__init_flag: 12 self.name = name 13 danli.__init_flag = False 14 15 a = danli('s') 16 print(a) 17 b = danli('d') 18 print(b)