class Singelton(object): __instance=None def __init__(self): pass def __new__(cls,*kwd,**kwargs): # if Singelton.__instance is None: # cls.__instance=object.__new__(cls,*kwd,**kwargs) return Singelton.__instance class a(Singleton): def __init__(self,x): self.a=x a1=a(5) a2=a(6) print a1.a print a2.a print id(a1),id(a2)
思路,利用__new__这个 类方法比__init__这个实例方法先运行的特点,直接返回类的实例,