ในภาษาไพทอน จะลบตัวแปล หรือ อ๊ออฟเจ็คที่ไม่ได้ใช้ อัตโนมัตร เพื่อคืนพื้นที่ในหน่วยความจำให้ระบบ ตัวแปลสามารถทำลายได้ด้วย del
เช่น
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
ส่วนในคลาส จะใช้ เรียกใช้ method __del__() เป็น destructor
ตัวอย่าง class_destroying_objects.py
# ตัวอย่าง class_destroying_objects.py
class MindpPoint:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
print ( " เริ่มเรียกใช้ Class")
def __del__(self):
class_name = self.__class__.__name__
print (class_name, " ถูกยกเลิก")
pt1 = MindpPoint()
pt2 =pt1
pt3 = pt2
print (id(pt1))
print (id(pt2))
print (id(pt3)) # แสดง ids ของ obejcts
ผลที่ได้
เริ่มเรียกใช้ Class
41397832
41397832
41397832
MindpPoint ถูกยกเลิก