new()方法是構造方法,init()方法是初始化方法,new()在init()以前執行,由new()建立一個對象,供init()初始化。框架
new()纔是真正的實例化方法,爲類提供外殼製造出實例框架,而後調用該框架內的構造方法init()使其豐滿。spa
class A: def __init__(self): print('init function') def __new__(cls, *args, **kwargs): print('new function') return object.__new__(A) a = A()
#先執行new()方法,再執行init()方法
out:new function
init function
下面建立的兩個對象其實在同一塊內存,即同一對象。code
class Singleton: def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): cls._instance = object.__new__(cls) return cls._instance one = Singleton() two = Singleton() two.a = 3 print(one.a) # 3 # one和two徹底相同,能夠用id(), ==, is檢測 print(id(one)) # 29097904 print(id(two)) # 29097904 print(one == two) # True print(one is two)