Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Garbage Collection ใน Python ทำงานอย่างไร

Python ลบออบเจ็กต์ที่ไม่ต้องการ (Built-in Types หรือ Class Instances) อัตโนมัติ เพื่อ釋放 Memory กระบวนการที่ Python ระงับและคืนบล็อก Memory ที่ไม่ได้ใช้แล้วเป็นระยะ เรียกว่า Garbage Collection

Garbage Collector ของ Python ทำงานระหว่างโปรแกรมรัน และถูก Trigger เมื่อ Reference Count ของออบเจ็กต์ถึงศูนย์ Reference Count เปลี่ยนตามจำนวน Aliases ที่ชี้ไปยังมัน

  • Reference Count เพิ่ม: กำหนดชื่อใหม่ ใส่ใน Container (List, Tuple, Dict)
  • Reference Count ลด: ลบด้วย del กำหนด Reference ใหม่ หรือ Reference ออกขอบเขต (Out of Scope)
  • เมื่อ Reference Count = 0 Python จะ Collect อัตโนมัติ
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>

ปกติจะไม่รู้สึกว่า Garbage Collector ทำลาย Instance Orphan และคืนพื้นที่ แต่คลาสสามารถ Implement __del__() (Destructor) ได้ เรียกตอน Instance จะถูกทำลาย ใช้ Cleanup Non-memory Resources

ตัวอย่าง

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __del__(self):
        class_name = self.__class__.__name__
        print(class_name, "destroyed")

pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3))
del pt1
del pt2
del pt3

ผลลัพธ์

3083401324 3083401324 3083401324
Point destroyed