__new__方法
- 這個方法是用來生成類的實例
class Singleton(object):
def __new__(cls,*args, **kwargs): ①
if not hasattr(cls,'_inst'):
print(cls)
cls._inst = super(Singleton, cls).__new__(cls) ②
return cls._inst ②
① 第一個參數必須是"要進行實例化的類".
② 返回實例完成的結果,如果實例化失敗那么實例的初始化函數"init"肯定不會執行
Python2(2.7)的寫法
class Singleton(object):
def __new__(cls,*args, **kwargs): ①
if not hasattr(cls,'_inst'):
print(cls)
cls._inst = super(Singleton, cls).__new__(cls,*args,**kwargs) ②
return cls._inst ②
Python3(3.5)的寫法
class Singleton(object):
def __new__(cls,*args, **kwargs): ①
if not hasattr(cls,'_inst'):
print(cls)
cls._inst = super(Singleton, cls).__new__(cls) ②
return cls._inst ②
如果Python3的寫法跟Python2寫法一樣,那么倒數第二行會報錯"TypeError: object() takes no parameters"