pyhton用__new__來創建對象(__new__相當於Java中的構建函數),
對象創建好之后會立即調用__init__方法來初始化對象,__init__方法有個參數self就是剛才__new__創建好的那個對象。通過我們有__init__方法中給對象的屬性進行賦值,或者動態線對象添加屬性並賦值
class test(object): count = 0 def __new__(cls, *args, **kwargs): test.count += 1 if test.count >2: raise Exception("大於2次實例化") return super(test, cls).__new__(cls) def __init__(self,a): self.a = a test0 = test('c') test1 = test('b') # test3 = test('a') print(test1.count) del test1
del test0
print(test1.count)
當使用del objectname時則銷毀這個對象的實例,當這個對象的引用計數為0的時候,就會被回收