對象的__del__是對象在被gc消除回收的時候起作用的一個方法,它的執行一般也就意味着對象不能夠繼續引用。
示范代碼如下:
1
2
3
4
5
6
7
8
9
|
class
Demo:
def
__del__(
self
):
print
(
"calling __del__"
)
obj
=
Demo()
del
obj
|
程序執行結果如下:
1
2
3
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
|
但是,這並不是讓__del__執行的唯一方式。其實,這個方法也可以直接調用。測試代碼如下:
1
2
3
4
5
6
7
8
9
|
class
Demo:
def
__init__(
self
):
print
(
"calling __del__"
)
obj
=
Demo()
obj.__del__()
|
程序執行結果:
1
2
3
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
|
但是,這樣的執行很多時候並不能夠保證垃圾回收的正常執行。
如下代碼:
1
2
3
4
5
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
calling __del__
|
執行結果:
1
2
3
4
5
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
calling __del__
|
推測:上面的刪除方法觸發了兩次刪除,但是由於引用關系,刪除銷毀其實沒有實現。
修改代碼驗證如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class
Demo:
def
__del__(
self
):
print
(
"calling __del__"
)
del
self
obj
=
Demo()
obj.__del__()
print
(
id
(obj))
|
執行結果:
1
2
3
4
5
6
7
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
140726800222040
calling __del__
|
從上面看來,其實主要還有對對象的引用,這個銷毀的動作還是需要等待對象引用沒有了以后才能夠完成。進一步驗證代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class
Demo:
def
__del__(
self
):
print
(
"calling __del__"
)
del
self
obj
=
Demo()
obj.__del__()
print
(
id
(obj))
print
(
id
(obj))
|
執行結果:
1
2
3
4
5
6
7
8
9
|
grey@DESKTOP
-
3T80NPQ
:
/
mnt
/
e
/
01_workspace
/
02_programme_language
/
03_python
/
03_OOP
/
2017
/
08
$python del_method.py
calling __del__
140568015406936
140568015406936
calling __del__
|
從上面結果看,猜測還是准確的。