例子一:
class B:
def __del__(self):
print(”內(nèi)存被釋放“)
b1 = B()
b2 = b1
print("hello world")
結(jié)果:
hello world #先打印
--------i am over------ #后打印
上面例子說明,程序結(jié)束時(shí)根资,python解釋器會自動調(diào)用del方法
不管是手動調(diào)用del還是由python自動回收都會觸發(fā)del方法執(zhí)行
例子二:
class B:
def __del__(self):
print("--------i am over------")
b1 = B()
del b1
print("hello world")
結(jié)果:
--------i am over------
hello world
刪除b1的時(shí)候钓丰,對象的引用計(jì)數(shù)器由1變?yōu)?缆娃,調(diào)用了del方法
例子三:
class B:
def __del__(self):
print("--------i am over------")
b1 = B()
b2 = b1
del b1
print("hello world")
結(jié)果:
hello world #先
--------i am over------ #后
b1 與 b2 都指向該內(nèi)存對象亏较,引用計(jì)數(shù)器為2遏佣,但是只刪除了b1塔逃,所以引用計(jì)數(shù)變?yōu)?
最后程序結(jié)束讯壶,自動調(diào)用del 方法
例子四:
class B:
def __del__(self):
print("--------i am over------")
b1 = B()
b2 = b1
del b1
del b2
print("hello world")
結(jié)果:
--------i am over------
hello world
刪除b1與b2,引用計(jì)數(shù)器歸0
如何查看引用計(jì)數(shù)器數(shù)量
import sys
class B:
def __del__(self):
print("--------i am over------")
b1 = B()
print(sys.getrefcount(b1)) #2
b2 = b1
print(sys.getrefcount(b1)) #3
print(sys.getrefcount(b2)) #3
del b1
print(sys.getrefcount(b2)) #2
del b2
print("hello world")
使用sys.getrefcount() 方法來獲取引用計(jì)數(shù)器的值湾盗,但該值會默認(rèn)+1